import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { TaskFormDialog, type TaskFormValues } from './TaskFormDialog';

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  defaultProjectId?: string;
  defaultStatus?: string;
}

export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultStatus }: Props) {
  const utils = trpc.useUtils();
  const { notify, notifyError } = useNotify();
  const create = trpc.tasks.create.useMutation({
    onSuccess: () => {
      notify('success', 'toast.task.created');
      void utils.tasks.list.invalidate();
      onOpenChange(false);
    },
    onError: (err) => notifyError('toast.task.createError', err),
  });

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

  return (
    <TaskFormDialog
      open={open}
      onOpenChange={onOpenChange}
      mode="create"
      initialValues={{
        projectId: defaultProjectId ?? null,
        status: defaultStatus ?? 'todo',
      }}
      onSubmit={handleSubmit}
      isSubmitting={create.isPending}
    />
  );
}
