"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 { DocumentForm } from "@/components/documents/document-form";
import { useDocument, useUpdateDocument } from "@/lib/hooks/use-documents";
import { useDataProvider } from "@/lib/demo/data-provider-context";

interface EditDocumentPageProps {
  params: Promise<{ id: string }>;
}

export default function EditDocumentPage({ params }: EditDocumentPageProps) {
  const { id: rawId } = use(params);
  const id = Number(rawId);
  const router = useRouter();
  const { basePath } = useDataProvider();

  const { data: document, isLoading, error, refetch } = useDocument(id);
  const updateDocument = useUpdateDocument(id);

  if (isLoading) {
    return (
      <div className="space-y-6">
        <LoadingSkeleton variant="detail" />
      </div>
    );
  }

  if (error || !document) {
    return (
      <div className="space-y-6">
        <ErrorBanner
          message="Failed to load document."
          onRetry={() => refetch()}
        />
      </div>
    );
  }

  return (
    <div className="space-y-6 w-full max-w-2xl mx-auto">
      <PageHeader
        title="Edit Document"
        description={document.title}
      />

      <DocumentForm
        document={document}
        loading={updateDocument.isPending}
        onSubmit={(data) => {
          updateDocument.mutate(data, {
            onSuccess: () => {
              toast.success("Document updated");
              router.push(`${basePath}/documents/${id}`);
            },
            onError: () => {
              toast.error("Failed to update document");
            },
          });
        }}
      />
    </div>
  );
}
