"use client";

import { use, useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  Pencil,
  Trash2,
  Download,
  FileText,
} from "lucide-react";
import { format } from "date-fns";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { WarrantyStatus } from "@/components/documents/warranty-status";
import { ImageGallery } from "@/components/documents/image-gallery";
import { useDocument, useDeleteDocument } from "@/lib/hooks/use-documents";
import { useDataProvider } from "@/lib/demo/data-provider-context";

const typeLabels: Record<string, string> = {
  general: "General",
  warranty: "Warranty",
  receipt: "Receipt",
  contract: "Contract",
  insurance: "Insurance",
  manual: "Manual",
};

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

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

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

  const [deleteOpen, setDeleteOpen] = useState(false);

  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>
    );
  }

  const isWarranty = document.document_type === "warranty";

  const warrantyDetails = [
    { label: "Vendor", value: document.vendor },
    { label: "Serial Number", value: document.serial_number },
    { label: "Model Number", value: document.model_number },
    {
      label: "Purchase Date",
      value: document.purchase_date
        ? format(new Date(document.purchase_date), "MMM d, yyyy")
        : undefined,
    },
    {
      label: "Expiry Date",
      value: document.expiry_date
        ? format(new Date(document.expiry_date), "MMM d, yyyy")
        : undefined,
    },
    {
      label: "Purchase Price",
      value:
        document.purchase_price != null
          ? `$${document.purchase_price.toFixed(2)}`
          : undefined,
    },
  ].filter((d) => d.value);

  return (
    <div className="space-y-6">
      <PageHeader title={document.title}>
        <Button
          variant="outline"
          size="sm"
          onClick={() => router.push(`${basePath}/documents/${id}/edit`)}
        >
          <Pencil className="size-4 mr-2" />
          Edit
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={() => setDeleteOpen(true)}
        >
          <Trash2 className="size-4 mr-2" />
          Delete
        </Button>
      </PageHeader>

      {/* Type badge & residence */}
      <div className="flex flex-wrap items-center gap-3">
        <Badge variant="outline">
          {typeLabels[document.document_type] ?? document.document_type}
        </Badge>
        <span className="text-sm text-muted-foreground">
          {document.residence_name}
        </span>
        {isWarranty && <WarrantyStatus expiry_date={document.expiry_date} />}
      </div>

      {/* Description */}
      {document.description && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm text-muted-foreground">
              Description
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm whitespace-pre-wrap">
              {document.description}
            </p>
          </CardContent>
        </Card>
      )}

      {/* Warranty Details */}
      {isWarranty && warrantyDetails.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm text-muted-foreground">
              Warranty Details
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
              {warrantyDetails.map((d) => (
                <div key={d.label}>
                  <p className="text-xs text-muted-foreground">{d.label}</p>
                  <p className="text-sm font-medium">{d.value}</p>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Images */}
      {document.images && document.images.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm text-muted-foreground">
              Images
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ImageGallery images={document.images} />
          </CardContent>
        </Card>
      )}

      {/* File Download */}
      {document.file_url && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm text-muted-foreground">
              Attached File
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-3">
              <div className="rounded-md bg-muted p-2">
                <FileText className="size-5 text-muted-foreground" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium truncate">
                  {document.file_name || "Download file"}
                </p>
                {document.file_size != null && (
                  <p className="text-xs text-muted-foreground">
                    {(document.file_size / 1024).toFixed(0)} KB
                  </p>
                )}
              </div>
              <Button variant="outline" size="sm" asChild>
                <a
                  href={document.file_url}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <Download className="size-4 mr-2" />
                  Download
                </a>
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Meta info */}
      <div className="text-xs text-muted-foreground">
        Created {format(new Date(document.created_at), "MMM d, yyyy")} by{" "}
        {document.created_by.first_name} {document.created_by.last_name}
      </div>

      {/* Delete Dialog */}
      <ConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title="Delete Document"
        description="Are you sure you want to delete this document? This action cannot be undone."
        confirmLabel="Delete"
        variant="destructive"
        loading={deleteDocument.isPending}
        onConfirm={() => {
          deleteDocument.mutate(id, {
            onSuccess: () => {
              toast.success("Document deleted");
              router.push(`${basePath}/documents`);
            },
            onError: () => {
              toast.error("Failed to delete document");
            },
          });
        }}
      />
    </div>
  );
}
