"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 { ContractorForm } from "@/components/contractors/contractor-form";
import { useContractor, useUpdateContractor } from "@/lib/hooks/use-contractors";
import { useDataProvider } from "@/lib/demo/data-provider-context";
import type { ContractorFormValues } from "@/components/contractors/contractor-form";

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

  const { data: contractor, isLoading, isError, error, refetch } = useContractor(id);
  const updateContractor = useUpdateContractor(id);

  function handleSubmit(data: ContractorFormValues) {
    updateContractor.mutate(data, {
      onSuccess: () => {
        toast.success("Contractor updated");
        router.push(`${basePath}/contractors/${id}`);
      },
      onError: () => {
        toast.error("Failed to update contractor");
      },
    });
  }

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

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

  if (!contractor) return null;

  return (
    <div className="space-y-6 w-full max-w-2xl mx-auto">
      <PageHeader title={`Edit ${contractor.name}`} />
      <ContractorForm
        contractor={contractor}
        onSubmit={handleSubmit}
        loading={updateContractor.isPending}
      />
    </div>
  );
}
