"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 { TaskCompletionForm } from "@/components/tasks/task-completion-form";
import { useTask, useCreateCompletion } from "@/lib/hooks/use-tasks";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function CompleteTaskPage({
  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 createCompletion = useCreateCompletion();

  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">
      <PageHeader
        title="Complete Task"
        description={task.title}
      />

      <Card>
        <CardContent>
          <TaskCompletionForm
            onSubmit={(data, images) => {
              createCompletion.mutate(
                {
                  data: {
                    task_id: taskId,
                    completed_at: data.completed_at,
                    actual_cost: data.actual_cost,
                    notes: data.notes,
                    rating: data.rating,
                  },
                  images,
                },
                {
                  onSuccess: () => {
                    toast.success("Task completed");
                    router.push(`${basePath}/tasks/${taskId}`);
                  },
                  onError: () => {
                    toast.error("Failed to complete task");
                  },
                },
              );
            }}
            isSubmitting={createCompletion.isPending}
          />
        </CardContent>
      </Card>
    </div>
  );
}
