"use client";

import { useQuery } from "@tanstack/react-query";
import { useRef } from "react";
import { FileDown, X } from "lucide-react";
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
  DrawerDescription,
} from "@/app/shadcn_components/ui/drawer";
import type { PropertyDocument, DocStatus } from "./types";
import PropertyDocumentsContent from "./PropertyDocumentsContent";

// -----------------------------------------------------------------------
// PropertyDrawer — main component
// -----------------------------------------------------------------------
interface PropertyDrawerProps {
  open: boolean;
  dealId?: string | null;
  uprn: string | null;
  landlordPropertyId: string | null;
  dealname: string | null;
  batch?: string | null;
  batchDescription?: string | null;
  docStatus?: DocStatus;
  onClose: () => void;
}

export default function PropertyDrawer({
  open,
  dealId,
  uprn,
  landlordPropertyId,
  dealname,
  batch,
  batchDescription,
  docStatus,
  onClose,
}: PropertyDrawerProps) {
  const canQuery = !!(dealId || uprn || landlordPropertyId);
  const {
    data: fetchedDocuments = [],
    isFetching,
    isError,
  } = useQuery({
    queryKey: ["property-documents", dealId, uprn, landlordPropertyId],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (dealId) params.set("dealId", dealId);
      else if (uprn) params.set("uprn", uprn);
      else if (landlordPropertyId)
        params.set("landlordPropertyId", landlordPropertyId);
      const res = await fetch(`/api/live-tracking/property-documents?${params}`);
      if (!res.ok) throw new Error("Failed to load documents");
      return res.json() as Promise<PropertyDocument[]>;
    },
    enabled: open && canQuery,
    staleTime: 30_000,
  });

  // Preserve last fetched docs so the closing animation doesn't flash empty state
  // when the parent nulls identifiers mid-animation.
  const lastDocumentsRef = useRef<PropertyDocument[]>([]);
  if (open && !isFetching && !isError) {
    lastDocumentsRef.current = fetchedDocuments as PropertyDocument[];
  }
  const documents = open ? (fetchedDocuments as PropertyDocument[]) : lastDocumentsRef.current;

  return (
    <Drawer open={open} onOpenChange={(v) => !v && onClose()} direction="right">
      <DrawerContent className="fixed right-0 top-0 bottom-0 h-full w-[40vw] min-w-80 rounded-l-2xl rounded-r-none mt-0 flex flex-col border-l border-t-0 border-b-0 border-r-0 border-brandblue/10 bg-white shadow-2xl overflow-hidden">
        <div className="hidden" />

        <DrawerHeader className="shrink-0 px-6 pt-6 pb-4 border-b border-gray-100">
          <div className="flex items-start justify-between gap-3">
            <div className="min-w-0 flex-1">
              <DrawerTitle className="text-lg font-semibold text-brandblue leading-tight line-clamp-2">
                {dealname ?? "Property Documents"}
              </DrawerTitle>
              {uprn ? (
                <DrawerDescription className="text-xs text-gray-500 mt-0.5 font-mono truncate">
                  UPRN: {uprn}
                </DrawerDescription>
              ) : landlordPropertyId ? (
                <DrawerDescription className="text-xs text-gray-500 mt-0.5 font-mono truncate">
                  Ref: {landlordPropertyId}
                </DrawerDescription>
              ) : null}
              {batch && (
                <p className="text-xs text-gray-500 mt-1 truncate">
                  Group:{" "}
                  <span className="font-mono text-gray-700">{batch}</span>
                  {batchDescription ? (
                    <span className="text-gray-500"> — {batchDescription}</span>
                  ) : null}
                </p>
              )}
            </div>
            <DrawerClose asChild>
              <button
                onClick={onClose}
                className="shrink-0 p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors"
              >
                <X className="h-4 w-4" />
              </button>
            </DrawerClose>
          </div>

          {documents.length > 0 && !isFetching && (
            <div className="mt-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-brandblue/10 border border-brandblue/20">
              <FileDown className="h-3.5 w-3.5 text-brandblue" />
              <span className="text-xs font-medium text-brandblue">
                {documents.length} document{documents.length !== 1 ? "s" : ""}
              </span>
            </div>
          )}
        </DrawerHeader>

        <div className="flex-1 overflow-y-auto px-6 py-4">
          <PropertyDocumentsContent
            documents={documents}
            isFetching={isFetching}
            isError={isError}
            docStatus={docStatus ?? { presentSurveyTypes: [], hasSurveyDocs: false, isSurveyComplete: false, hasInstallDocs: false, installStatus: "none", measureProgress: [] }}
          />
        </div>

        <div className="px-6 py-4 border-t border-gray-100 bg-gray-50/50">
          <p className="text-xs text-gray-400">
            Download links expire after 30 minutes. Refresh to generate a new link.
          </p>
        </div>
      </DrawerContent>
    </Drawer>
  );
}
