"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { toast } from "sonner";
import { PageHeader } from "@/components/shared/page-header";
import { Card, CardContent } from "@/components/ui/card";
import { TaskForm } from "@/components/tasks/task-form";
import { useCreateTask } from "@/lib/hooks/use-tasks";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function NewTaskPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { basePath } = useDataProvider();
  const createTask = useCreateTask();

  const residenceId = searchParams.get("residence_id");
  const defaultResidenceId = residenceId ? Number(residenceId) : undefined;

  return (
    <div className="space-y-6 w-full max-w-2xl mx-auto">
      <PageHeader title="New Task" />

      <Card>
        <CardContent>
          <TaskForm
            defaultResidenceId={defaultResidenceId}
            onSubmit={(data) => {
              createTask.mutate(data, {
                onSuccess: () => {
                  toast.success("Task created");
                  if (defaultResidenceId) {
                    router.push(`${basePath}/residences/${defaultResidenceId}`);
                  } else {
                    router.push(`${basePath}/tasks`);
                  }
                },
                onError: () => {
                  toast.error("Failed to create task");
                },
              });
            }}
            isSubmitting={createTask.isPending}
          />
        </CardContent>
      </Card>
    </div>
  );
}
