import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { TaskFormDialog, type TaskFormValues } from './TaskFormDialog';
import type { TaskItem } from './task-types';
import { parseAssignees } from './task-utils';

interface Props {
  task: TaskItem | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function EditTaskDialog({ task, open, onOpenChange }: Props) {
  const utils = trpc.useUtils();
  const { notify, notifyError } = useNotify();
  const update = trpc.tasks.update.useMutation({
    onSuccess: () => {
      notify('success', 'toast.task.updated');
      void utils.tasks.list.invalidate();
      onOpenChange(false);
    },
    onError: (err) => notifyError('toast.task.updateError', err),
  });

  if (!task) return null;
  const taskId = task.id;

  function handleSubmit(values: TaskFormValues) {
    update.mutate({
      id: taskId,
      title: values.title,
      description: values.description || undefined,
      priority: values.priority,
      status: values.status,
      dueDate: values.dueDate ?? undefined,
      projectId: values.projectId ?? undefined,
      assignees: values.assignees,
      estimate: values.estimate,
    });
  }

  return (
    <TaskFormDialog
      open={open}
      onOpenChange={onOpenChange}
      mode="edit"
      taskId={taskId}
      initialValues={{
        title: task.title,
        description: task.description ?? '',
        priority: task.priority ?? 'medium',
        status: task.status ?? 'todo',
        dueDate: task.dueDate ?? null,
        projectId: task.projectId ?? null,
        assignees: parseAssignees(task.assignee),
        estimate: task.estimate ?? null,
      }}
      onSubmit={handleSubmit}
      isSubmitting={update.isPending}
    />
  );
}
