"use client";

import { useState, useTransition, useMemo } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { FileText, ChevronRight, ChevronDown, X, Loader2, RefreshCw } from "lucide-react";
import { fetchVendorUploadedFiles, cancelVendorUploadedFile } from "../vendor-actions";
import type { SwpFileApiResponse } from "../api-client";

interface SwpUploadedFilesDialogProps {
  projNo: string;
  vndrCd: string; // UI 표시용으로만 사용
  userId: string;
}

interface FileTreeNode {
  files: SwpFileApiResponse[];
}

interface RevisionTreeNode {
  revNo: string;
  files: FileTreeNode;
}

interface DocumentTreeNode {
  docNo: string;
  revisions: Map<string, RevisionTreeNode>;
}

export function SwpUploadedFilesDialog({ projNo, vndrCd, userId }: SwpUploadedFilesDialogProps) {
  const [open, setOpen] = useState(false);
  const [files, setFiles] = useState<SwpFileApiResponse[]>([]);
  const [isLoading, startLoading] = useTransition();
  const [expandedDocs, setExpandedDocs] = useState<Set<string>>(new Set());
  const [expandedRevs, setExpandedRevs] = useState<Set<string>>(new Set());
  const [cancellingFiles, setCancellingFiles] = useState<Set<string>>(new Set());
  const { toast } = useToast();

  // 파일 목록을 트리 구조로 변환
  const fileTree = useMemo(() => {
    const tree = new Map<string, DocumentTreeNode>();

    files.forEach((file) => {
      const docNo = file.OWN_DOC_NO;
      const revNo = file.REV_NO;

      if (!tree.has(docNo)) {
        tree.set(docNo, {
          docNo,
          revisions: new Map(),
        });
      }

      const docNode = tree.get(docNo)!;

      if (!docNode.revisions.has(revNo)) {
        docNode.revisions.set(revNo, {
          revNo,
          files: { files: [] },
        });
      }

      const revNode = docNode.revisions.get(revNo)!;
      revNode.files.files.push(file);
    });

    return tree;
  }, [files]);

  // 다이얼로그 열릴 때 파일 목록 조회
  const handleOpenChange = (newOpen: boolean) => {
    setOpen(newOpen);
    if (newOpen) {
      loadFiles();
    }
  };

  // 파일 목록 조회
  const loadFiles = () => {
    if (!projNo) {
      toast({
        variant: "destructive",
        title: "Unable to retrieve files",
        description: "Project information is required.",
      });
      return;
    }

    startLoading(async () => {
      try {
        // vndrCd는 서버에서 세션으로 자동 조회
        const result = await fetchVendorUploadedFiles(projNo);
        setFiles(result);
        toast({
          title: "Files retrieved successfully",
          description: `${result.length} files retrieved.`,
        });
      } catch (error) {
        console.error("Failed to retrieve files:", error);
        toast({
          variant: "destructive",
          title: "Failed to retrieve files",
          description: error instanceof Error ? error.message : "Unknown error",
        });
      }
    });
  };

  // 파일 취소
  const handleCancelFile = async (file: SwpFileApiResponse) => {
    if (!file.BOX_SEQ || !file.ACTV_SEQ) {
      toast({
        variant: "destructive",
        title: "Unable to cancel file",
        description: "File information is invalid.",
      });
      return;
    }

    const fileKey = `${file.BOX_SEQ}_${file.ACTV_SEQ}`;
    setCancellingFiles((prev) => new Set(prev).add(fileKey));

    try {
      await cancelVendorUploadedFile({
        boxSeq: file.BOX_SEQ,
        actvSeq: file.ACTV_SEQ,
        userId,
      });

      toast({
        title: "File canceled successfully",
        description: `${file.FILE_NM} file canceled.`,
      });

      // 목록 새로고침
      loadFiles();
    } catch (error) {
      console.error("Failed to cancel file:", error);
      toast({
        variant: "destructive",
        title: "Failed to cancel file",
        description: error instanceof Error ? error.message : "Unknown error",
      });
    } finally {
      setCancellingFiles((prev) => {
        const newSet = new Set(prev);
        newSet.delete(fileKey);
        return newSet;
      });
    }
  };

  // 문서 토글
  const toggleDoc = (docNo: string) => {
    setExpandedDocs((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(docNo)) {
        newSet.delete(docNo);
      } else {
        newSet.add(docNo);
      }
      return newSet;
    });
  };

  // 리비전 토글
  const toggleRev = (docNo: string, revNo: string) => {
    const key = `${docNo}_${revNo}`;
    setExpandedRevs((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(key)) {
        newSet.delete(key);
      } else {
        newSet.add(key);
      }
      return newSet;
    });
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" disabled={!projNo}>
          <FileText className="h-4 w-4 mr-2" />
          Upload File Management
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle>Uploaded File List</DialogTitle>
          <DialogDescription>
            Project: {projNo} | Company: {vndrCd}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 액션 바 */}
          <div className="flex items-center justify-between">
            <div className="text-sm text-muted-foreground">
              Total {files.length} files
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={loadFiles}
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Loading...
                </>
              ) : (
                <>
                  <RefreshCw className="h-4 w-4 mr-2" />
                  Refresh
                </>
              )}
            </Button>
          </div>

          {/* 파일 트리 */}
          <ScrollArea className="h-[500px] rounded-md border p-4">
            {isLoading && files.length === 0 ? (
              <div className="flex items-center justify-center h-full text-muted-foreground">
                <Loader2 className="h-6 w-6 animate-spin mr-2" />
                Loading files...
              </div>
            ) : files.length === 0 ? (
              <div className="flex items-center justify-center h-full text-muted-foreground">
                No files uploaded.
              </div>
            ) : (
              <div className="space-y-2">
                {Array.from(fileTree.entries()).map(([docNo, docNode]) => (
                  <div key={docNo} className="space-y-1">
                    {/* 문서번호 */}
                    <div
                      className="flex items-center gap-2 p-2 rounded-md hover:bg-muted cursor-pointer"
                      onClick={() => toggleDoc(docNo)}
                    >
                      {expandedDocs.has(docNo) ? (
                        <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
                      ) : (
                        <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
                      )}
                      <FileText className="h-4 w-4 text-blue-600 shrink-0" />
                      <span className="font-semibold">{docNo}</span>
                      <Badge variant="outline" className="text-xs">
                        {docNode.revisions.size} revisions
                      </Badge>
                    </div>

                    {/* 리비전 목록 */}
                    {expandedDocs.has(docNo) && (
                      <div className="ml-6 space-y-1">
                        {Array.from(docNode.revisions.entries()).map(([revNo, revNode]) => {
                          const revKey = `${docNo}_${revNo}`;
                          return (
                            <div key={revKey} className="space-y-1">
                              {/* 리비전 번호 */}
                              <div
                                className="flex items-center gap-2 p-2 rounded-md hover:bg-muted cursor-pointer"
                                onClick={() => toggleRev(docNo, revNo)}
                              >
                                {expandedRevs.has(revKey) ? (
                                  <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
                                ) : (
                                  <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
                                )}
                                <span className="font-medium text-sm">Rev: {revNo}</span>
                                <Badge variant="secondary" className="text-xs">
                                  {revNode.files.files.length} files
                                </Badge>
                              </div>

                              {/* 파일 목록 */}
                              {expandedRevs.has(revKey) && (
                                <div className="ml-6 space-y-1">
                                  {revNode.files.files.map((file, idx) => {
                                    const fileKey = `${file.BOX_SEQ}_${file.ACTV_SEQ}`;
                                    const isCancellable = file.STAT === "SCW01";
                                    const isCancelling = cancellingFiles.has(fileKey);

                                    return (
                                      <div
                                        key={`${fileKey}_${idx}`}
                                        className="flex items-center gap-2 p-2 rounded-md border bg-card"
                                      >
                                        <FileText className="h-4 w-4 text-muted-foreground shrink-0" />
                                        <div className="flex-1 min-w-0">
                                          <div className="text-sm truncate">{file.FILE_NM}</div>
                                          <div className="flex items-center gap-2 text-xs text-muted-foreground">
                                            <span>Stage: {file.STAGE}</span>
                                            <span>•</span>
                                            <span>Status: {file.STAT_NM || file.STAT || "Unknown"}</span>
                                          </div>
                                        </div>
                                        <Button
                                          variant="destructive"
                                          size="sm"
                                          onClick={() => handleCancelFile(file)}
                                          disabled={!isCancellable || isCancelling}
                                          title={
                                            isCancellable
                                              ? "Cancel file upload"
                                              : `Cancel not possible (Status: ${file.STAT_NM || file.STAT})`
                                          }
                                        >
                                          {isCancelling ? (
                                            <>
                                              <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                                              Canceling...
                                            </>
                                          ) : (
                                            <>
                                              <X className="h-3 w-3 mr-1" />
                                              Cancel
                                            </>
                                          )}
                                        </Button>
                                      </div>
                                    );
                                  })}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </ScrollArea>

          {/* 안내 메시지 */}
          <div className="rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 p-3">
            <div className="text-xs text-blue-600 dark:text-blue-400 space-y-1">
              <p>Files in the 'SCW01' status can only be canceled.</p>
              <p>Canceled files will be removed from the list.</p>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
