
// "use client";

// import { useState } from "react";
// import {
//   Dialog,
//   DialogContent,
//   DialogHeader,
//   DialogTitle,
//   DialogFooter,
//   DialogDescription,
// } from "@/components/ui/dialog";
// import { Button } from "@/components/ui/button";
// import { Textarea } from "@/components/ui/textarea";
// import { Badge } from "@/components/ui/badge";
// import { FileText, ExternalLink, Check, X } from "lucide-react";
// import { TaskDocument } from "@/modules/client/task/type/task.type";
// import { useApproveTask } from "../hooks/task.hooks";

// interface DocumentVerifyDialogProps {
//   taskId: string;
//   documents: TaskDocument[];
//   open: boolean;
//   onClose: () => void;
// }

// const DOC_STATUS_STYLES: Record<string, string> = {
//   VERIFIED: "bg-green-500/15 text-green-700 border-green-200",
//   UPLOADED: "bg-yellow-500/15 text-yellow-700 border-yellow-200",
//   AI_VERIFIED: "bg-blue-500/15 text-blue-700 border-blue-200",
//   REJECTED: "bg-red-500/15 text-red-700 border-red-200",
// };

// export function DocumentVerifyDialog({
//   taskId,
//   documents,
//   open,
//   onClose,
// }: DocumentVerifyDialogProps) {
//   // remarks per document, keyed by doc id — only used if you reject that doc
//   const [remarksMap, setRemarksMap] = useState<Record<string, string>>({});
//   // which doc is currently submitting, so only that row shows a spinner state
//   const [actingDocId, setActingDocId] = useState<string | null>(null);

//   const { mutate, isPending } = useApproveTask(() => {
//     setActingDocId(null);
//   });

//   const allReviewed = documents.every(
//     (d) => d.status === "VERIFIED" || d.status === "REJECTED"
//   );

//   const handleDocAction = (docId: string, status: "VERIFIED" | "REJECTED") => {
//     setActingDocId(docId);
//     mutate({
//       taskId,
//       payload: {
//         documentIds: [docId],
//         status,
//         remarks: remarksMap[docId]?.trim() || undefined,
//       },
//     });
//   };

//   return (
//     <Dialog
//       open={open}
//       onOpenChange={(isOpen) => {
//         if (!isOpen) onClose();
//       }}
//     >
//       <DialogContent className="max-w-lg">
//         <DialogHeader>
//           <DialogTitle className="text-base">Verify Documents</DialogTitle>
//           <DialogDescription className="text-xs">
//             Review each document individually — verify or reject one at a time.
//           </DialogDescription>
//         </DialogHeader>

//         <div className="flex flex-col gap-2.5 max-h-[420px] overflow-y-auto pr-1">
//           {documents.map((doc) => {
//             const isDecided = false;
//             const isActing = isPending && actingDocId === doc.id;

//             return (
//               <div
//                 key={doc.id}
//                 className="rounded-lg border border-border bg-muted/30 px-3 py-2.5 space-y-2"
//               >
//                 <div className="flex items-start justify-between gap-3">
//                   <div className="flex items-start gap-2 min-w-0">
//                     <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground mt-0.5" />
//                     <div className="min-w-0">
//                       <p className="text-xs font-medium text-foreground truncate">
//                         {doc.serviceDocument?.name ?? doc.fileName}
//                       </p>
//                       {doc.fileSizeKb && (
//                         <p className="text-[10px] text-muted-foreground">
//                           {doc.fileSizeKb} KB
//                         </p>
//                       )}
//                     </div>
//                   </div>
//                   <div className="flex items-center gap-2 shrink-0">
//                     <Badge
//                       variant="outline"
//                       className={`text-[10px] ${DOC_STATUS_STYLES[doc.status] ?? "bg-muted text-muted-foreground"}`}
//                     >
//                       {doc.status}
//                     </Badge>
//                     <a
//                       href={doc.fileUrl}
//                       target="_blank"
//                       rel="noopener noreferrer"
//                       className="inline-flex items-center gap-1 text-[10px] text-blue-600 hover:underline"
//                     >
//                       View <ExternalLink className="h-3 w-3" />
//                     </a>
//                   </div>
//                 </div>

//                 {!isDecided && (
//                   <div className="space-y-1.5">
//                     <Textarea
//                       placeholder="Remarks (optional, e.g. reason for rejection)"
//                       value={remarksMap[doc.id] ?? ""}
//                       onChange={(e) =>
//                         setRemarksMap((prev) => ({ ...prev, [doc.id]: e.target.value }))
//                       }
//                       className="text-xs resize-none h-14"
//                     />
//                     <div className="flex items-center gap-2">
//                       <Button
//                         size="sm"
//                         variant="destructive"
//                         disabled={isPending}
//                         onClick={() => handleDocAction(doc.id, "REJECTED")}
//                         className="h-7 text-[11px] gap-1"
//                       >
//                         <X className="h-3 w-3" />
//                         {isActing ? "..." : "Reject"}
//                       </Button>
//                       <Button
//                         size="sm"
//                         disabled={isPending}
//                         onClick={() => handleDocAction(doc.id, "VERIFIED")}
//                         className="h-7 text-[11px] gap-1"
//                       >
//                         <Check className="h-3 w-3" />
//                         {isActing ? "..." : "Verify"}
//                       </Button>
//                     </div>
//                   </div>
//                 )}
//               </div>
//             );
//           })}
//         </div>

//         <DialogFooter>
//           <Button variant="outline" size="sm" onClick={onClose}>
//             {allReviewed ? "Done" : "Close"}
//           </Button>
//         </DialogFooter>
//       </DialogContent>
//     </Dialog>
//   );
// }


"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { FileText, ExternalLink, Check, X } from "lucide-react";
import { TaskDocument } from "@/modules/client/task/type/task.type";
import { useApproveTask } from "../hooks/task.hooks";

interface DocumentVerifyDialogProps {
  taskId: string;
  documents: TaskDocument[];
  open: boolean;
  onClose: () => void;
}

const DOC_STATUS_STYLES: Record<string, string> = {
  VERIFIED: "bg-green-500/15 text-green-700 border-green-200",
  UPLOADED: "bg-yellow-500/15 text-yellow-700 border-yellow-200",
  AI_VERIFIED: "bg-blue-500/15 text-blue-700 border-blue-200",
  REJECTED: "bg-red-500/15 text-red-700 border-red-200",
};

export function DocumentVerifyDialog({
  taskId,
  documents,
  open,
  onClose,
}: DocumentVerifyDialogProps) {
  // remarks per document, keyed by doc id — only used if you reject that doc
  const [remarksMap, setRemarksMap] = useState<Record<string, string>>({});
  // which doc is currently submitting, and which action, so only that button shows loading state
  const [actingDocId, setActingDocId] = useState<string | null>(null);
  const [actingStatus, setActingStatus] = useState<"VERIFIED" | "REJECTED" | null>(null);

  const { mutate, isPending } = useApproveTask(() => {
    setActingDocId(null);
    setActingStatus(null);
  });

  const allReviewed = documents.every(
    (d) => d.status === "VERIFIED" || d.status === "REJECTED"
  );

  const handleDocAction = (docId: string, status: "VERIFIED" | "REJECTED") => {
    setActingDocId(docId);
    setActingStatus(status);
    mutate({
      taskId,
      payload: {
        documentIds: [docId],
        status,
        remarks: remarksMap[docId]?.trim() || undefined,
      },
    });
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(isOpen) => {
        if (!isOpen) onClose();
      }}
    >
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle className="text-base">Verify Documents</DialogTitle>
          <DialogDescription className="text-xs">
            Review each document individually — verify or reject one at a time.
          </DialogDescription>
        </DialogHeader>

        <div className="flex flex-col gap-2.5 max-h-[420px] overflow-y-auto pr-1">
          {documents.map((doc) => {
            const isVerified = doc.status === "VERIFIED";
            const isRejected = doc.status === "REJECTED";
            const isThisDocActing = isPending && actingDocId === doc.id;

            return (
              <div
                key={doc.id}
                className="rounded-lg border border-border bg-muted/30 px-3 py-2.5 space-y-2"
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="flex items-start gap-2 min-w-0">
                    <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground mt-0.5" />
                    <div className="min-w-0">
                      <p className="text-xs font-medium text-foreground truncate">
                        {doc.serviceDocument?.name ?? doc.fileName}
                      </p>
                      {doc.fileSizeKb && (
                        <p className="text-[10px] text-muted-foreground">
                          {doc.fileSizeKb} KB
                        </p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <Badge
                      variant="outline"
                      className={`text-[10px] ${DOC_STATUS_STYLES[doc.status] ?? "bg-muted text-muted-foreground"}`}
                    >
                      {doc.status}
                    </Badge>
                    <a
                      href={doc.fileUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1 text-[10px] text-blue-600 hover:underline"
                    >
                      View <ExternalLink className="h-3 w-3" />
                    </a>
                  </div>
                </div>

                <div className="space-y-1.5">
                  <Textarea
                    placeholder="Remarks (optional, e.g. reason for rejection)"
                    value={remarksMap[doc.id] ?? ""}
                    onChange={(e) =>
                      setRemarksMap((prev) => ({ ...prev, [doc.id]: e.target.value }))
                    }
                    className="text-xs resize-none h-14"
                    disabled={isThisDocActing}
                  />
                  <div className="flex items-center gap-2">
                    <Button
                      size="sm"
                      variant="destructive"
                      disabled={isRejected || isPending}
                      onClick={() => handleDocAction(doc.id, "REJECTED")}
                      className="h-7 text-[11px] gap-1"
                    >
                      <X className="h-3 w-3" />
                      {isThisDocActing && actingStatus === "REJECTED" ? "..." : "Reject"}
                    </Button>
                    <Button
                      size="sm"
                      disabled={isVerified || isPending}
                      onClick={() => handleDocAction(doc.id, "VERIFIED")}
                      className="h-7 text-[11px] gap-1"
                    >
                      <Check className="h-3 w-3" />
                      {isThisDocActing && actingStatus === "VERIFIED" ? "..." : "Verify"}
                    </Button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <DialogFooter>
          <Button variant="outline" size="sm" onClick={onClose}>
            {allReviewed ? "Done" : "Close"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}