"use client";

import { use } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { Card, CardContent } from "@/components/ui/card";
import { TaskForm } from "@/components/tasks/task-form";
import { useTask, useUpdateTask } from "@/lib/hooks/use-tasks";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function EditTaskPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const taskId = Number(id);
  const router = useRouter();
  const { basePath } = useDataProvider();

  const { data: task, isLoading, isError, error, refetch } = useTask(taskId);
  const updateTask = useUpdateTask(taskId);

  if (isLoading) {
    return <LoadingSkeleton variant="detail" />;
  }

  if (isError) {
    return (
      <ErrorBanner
        message={
          error instanceof Error ? error.message : "Failed to load task"
        }
        onRetry={() => refetch()}
      />
    );
  }

  if (!task) return null;

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

      <Card>
        <CardContent>
          <TaskForm
            task={task}
            onSubmit={(data) => {
              updateTask.mutate(data, {
                onSuccess: () => {
                  toast.success("Task updated");
                  router.push(`${basePath}/tasks/${taskId}`);
                },
                onError: () => {
                  toast.error("Failed to update task");
                },
              });
            }}
            isSubmitting={updateTask.isPending}
          />
        </CardContent>
      </Card>
    </div>
  );
}
