"use client";

import React, { useState, useEffect, useMemo } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { 
  Loader2, 
  Download, 
  FileIcon,
  AlertCircle,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { 
  fetchGetRevTreeCompleteList,
  parseRevisionTree,
  fetchGetActivityFileList,
  type ActivityFileApiResponse,
} from "@/lib/swp/api-client";
import { downloadVendorFile } from "@/lib/swp/vendor-actions";
import type { DocumentListItem } from "@/lib/swp/document-service";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { formatSwpDateShort, formatFileSize } from "@/lib/swp/utils";

interface SwpDocumentDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  document: DocumentListItem | null;
  projNo: string;
  vendorCode: string;
  userId: string;
}

// Activity 행 데이터
interface ActivityRow {
  revNo: string;
  revSeq: string;
  stage: string;
  actvNo: string;
  inOut: "IN" | "OUT";
  statusCode: string;
  statusName: string;
  transmittalNo: string;
  refActivityNo: string;
  createDate: string;
  createEmpNo: string;
}

export function SwpDocumentDetailDialog({
  open,
  onOpenChange,
  document,
  projNo,
}: SwpDocumentDetailDialogProps) {
  const [activities, setActivities] = useState<ActivityRow[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedActivity, setSelectedActivity] = useState<ActivityRow | null>(null);
  const [activityFiles, setActivityFiles] = useState<ActivityFileApiResponse[]>([]);
  const [isLoadingFiles, setIsLoadingFiles] = useState(false);

  // 문서 상세 로드
  useEffect(() => {
    if (open && document) {
      loadDocumentDetail();
    } else {
      // 다이얼로그 닫힐 때 초기화
      setSelectedActivity(null);
      setActivityFiles([]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, document?.DOC_NO]);

  const loadDocumentDetail = async () => {
    if (!document) return;

    setIsLoading(true);
    setSelectedActivity(null);
    setActivityFiles([]);
    
    try {
      // GetRevTreeCompleteList 호출
      const tree = await fetchGetRevTreeCompleteList({
        proj_no: projNo,
        doc_no: document.DOC_NO,
      });

      const parsed = await parseRevisionTree(tree);

      // Activity를 flat한 배열로 변환 (테이블용)
      const flatActivities: ActivityRow[] = [];
      parsed.revisions.forEach((rev) => {
        rev.activities.forEach((act) => {
          flatActivities.push({
            revNo: rev.revNo,
            revSeq: rev.revSeq,
            stage: rev.stage,
            actvNo: act.actvNo,
            inOut: act.inOut,
            statusCode: act.statusCode,
            statusName: act.statusName,
            transmittalNo: act.transmittalNo,
            refActivityNo: act.refActivityNo,
            createDate: act.createDate,
            createEmpNo: act.createEmpNo,
          });
        });
      });

      setActivities(flatActivities);
    } catch (error) {
      console.error("문서 상세 조회 실패:", error);
      toast.error("문서 리비전 트리를 불러오는데 실패했습니다");
    } finally {
      setIsLoading(false);
    }
  };

  // Activity 선택 및 파일 로드
  const handleActivityClick = async (activity: ActivityRow) => {
    if (selectedActivity?.actvNo === activity.actvNo) {
      // 같은 Activity 클릭 시 토글
      setSelectedActivity(null);
      setActivityFiles([]);
      return;
    }

    setSelectedActivity(activity);
    setIsLoadingFiles(true);
    setActivityFiles([]);

    try {
      // GetActivityFileList 호출
      const files = await fetchGetActivityFileList({
        proj_no: projNo,
        doc_no: document?.DOC_NO || "",
        rev_seq: activity.revSeq,
      });

      // 해당 Activity의 파일만 필터링
      const activitySpecificFiles = files.filter(
        (f) => f.ACTV_NO === activity.actvNo
      );

      setActivityFiles(activitySpecificFiles);
    } catch (error) {
      console.error("파일 목록 조회 실패:", error);
      toast.error("파일 목록을 불러오는데 실패했습니다");
    } finally {
      setIsLoadingFiles(false);
    }
  };

  const handleDownloadFile = async (fileName: string, ownDocNo: string) => {
    try {
      toast.info("파일 다운로드 중...");
      const result = await downloadVendorFile(projNo, ownDocNo, fileName);
      
      if (!result.success || !result.data) {
        toast.error(result.error || "파일 다운로드 실패");
        return;
      }

      // Blob 생성 및 다운로드
      const blob = new Blob([Buffer.from(result.data)], { type: result.mimeType });
      const url = URL.createObjectURL(blob);
      const link = window.document.createElement("a");
      link.href = url;
      link.download = result.fileName || fileName;
      window.document.body.appendChild(link);
      link.click();
      window.document.body.removeChild(link);
      URL.revokeObjectURL(url);

      toast.success(`파일 다운로드 완료: ${fileName}`);
    } catch (error) {
      console.error("파일 다운로드 실패:", error);
      toast.error("파일 다운로드에 실패했습니다");
    }
  };

  // Revision별로 Activity 그룹핑 및 정렬 (rowspan용)
  const groupedActivities = useMemo(() => {
    // 1. REV 내림차순, createDate 내림차순으로 정렬
    const sortedActivities = [...activities].sort((a, b) => {
      // REV 비교 (내림차순)
      const revCompare = b.revNo.localeCompare(a.revNo);
      if (revCompare !== 0) return revCompare;
      
      // 같은 REV 내에서는 createDate 내림차순
      return b.createDate.localeCompare(a.createDate);
    });

    // 2. 그룹핑
    const groups: Map<string, ActivityRow[]> = new Map();
    sortedActivities.forEach((activity) => {
      const key = `${activity.revNo}|${activity.stage}`;
      if (!groups.has(key)) {
        groups.set(key, []);
      }
      groups.get(key)!.push(activity);
    });
    
    return groups;
  }, [activities]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="text-base">문서 리비전 히스토리</DialogTitle>
          {document && (
            <DialogDescription className="text-xs">
              {document.DOC_NO} - {document.DOC_TITLE}
            </DialogDescription>
          )}
        </DialogHeader>

        {document && (
          <div className="flex-1 flex flex-col space-y-2 overflow-hidden">
            {/* 문서 정보 */}
            <div className="flex items-center gap-4 px-3 py-2 bg-muted/30 rounded text-xs">
              <div className="flex items-center gap-1">
                <span className="font-semibold">프로젝트:</span>
                <span>{document.PROJ_NO}</span>
                {document.PROJ_NM && (
                  <span className="text-muted-foreground">({document.PROJ_NM})</span>
                )}
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">패키지:</span>
                <span>{document.PKG_NO || "-"}</span>
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">업체:</span>
                <span>{document.CPY_NM || "-"}</span>
                {document.VNDR_CD && (
                  <span className="text-muted-foreground">({document.VNDR_CD})</span>
                )}
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">최신 리비전:</span>
                <span>{document.LTST_REV_NO || "-"}</span>
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">총 Activity:</span>
                <span>{activities.length}개</span>
              </div>
            </div>

            {/* Activity 테이블 */}
            {isLoading ? (
              <div className="flex items-center justify-center p-8">
                <Loader2 className="h-5 w-5 animate-spin" />
                <span className="ml-2 text-sm">리비전 트리 로딩 중...</span>
              </div>
            ) : activities.length > 0 ? (
              <>
                {/* Activity 테이블 (위) */}
                <div className="h-[40vh] overflow-auto border rounded-lg">
                  <Table>
                    <TableHeader className="sticky top-0 bg-background z-10">
                      <TableRow className="text-xs">
                        <TableHead className="w-[70px] text-xs h-8">Rev</TableHead>
                        <TableHead className="w-[70px] text-xs h-8">Stage</TableHead>
                        <TableHead className="w-[70px] text-xs h-8">IN/OUT</TableHead>
                        <TableHead className="w-[90px] text-xs h-8">Status</TableHead>
                        <TableHead className="min-w-[130px] text-xs h-8">Transmittal No</TableHead>
                        <TableHead className="min-w-[130px] text-xs h-8">Activity No</TableHead>
                        <TableHead className="min-w-[90px] text-xs h-8">Ref Activity</TableHead>
                        <TableHead className="w-[100px] text-xs h-8">Modified</TableHead>
                        <TableHead className="w-[70px] text-xs h-8">By</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {Array.from(groupedActivities.entries()).map(([key, groupActivities]) => {
                        const [revNo, stage] = key.split("|");
                        return groupActivities.map((activity, idx) => (
                          <TableRow
                            key={activity.actvNo}
                            className={cn(
                              "cursor-pointer hover:bg-muted/50 h-8",
                              selectedActivity?.actvNo === activity.actvNo &&
                                "bg-blue-50 hover:bg-blue-100"
                            )}
                            onClick={() => handleActivityClick(activity)}
                          >
                            {/* Rev 컬럼 (첫 행만 표시, rowspan) */}
                            {idx === 0 && (
                              <TableCell 
                                className="font-mono text-xs font-semibold align-top border-r py-1"
                                rowSpan={groupActivities.length}
                              >
                                {revNo}
                              </TableCell>
                            )}
                            {/* Stage 컬럼 (첫 행만 표시, rowspan) */}
                            {idx === 0 && (
                              <TableCell 
                                className="align-top border-r text-xs py-1"
                                rowSpan={groupActivities.length}
                              >
                                {stage}
                              </TableCell>
                            )}
                            <TableCell className="py-1">
                              <Badge
                                variant="outline"
                                className={cn(
                                  "text-[10px] h-4 px-1",
                                  activity.inOut === "IN"
                                    ? "bg-blue-100 text-blue-800"
                                    : "bg-green-100 text-green-800"
                                )}
                              >
                                {activity.inOut}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              <div className="font-medium">{activity.statusName}</div>
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              {activity.transmittalNo || "-"}
                            </TableCell>
                            <TableCell className="font-mono text-xs py-1">
                              {activity.actvNo}
                            </TableCell>
                            <TableCell className="font-mono text-xs py-1">
                              {activity.refActivityNo || "-"}
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              {formatSwpDateShort(activity.createDate)}
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              {activity.createEmpNo}
                            </TableCell>
                          </TableRow>
                        ));
                      })}
                    </TableBody>
                  </Table>
                </div>

                {/* 파일 목록 (아래) */}
                <div className="border rounded-lg overflow-hidden h-[30vh] flex flex-col">
                  <div className="px-3 py-1.5 bg-muted/50 border-b flex-shrink-0">
                    <h3 className="font-semibold text-xs">파일 목록</h3>
                    {selectedActivity ? (
                      <p className="text-[10px] text-muted-foreground mt-0.5">
                        Activity: {selectedActivity.actvNo} / Rev {selectedActivity.revNo} ({selectedActivity.stage}) / {selectedActivity.inOut}
                      </p>
                    ) : (
                      <p className="text-[10px] text-muted-foreground mt-0.5">
                        Activity를 선택하면 파일 목록이 표시됩니다
                      </p>
                    )}
                  </div>
                  <div className="overflow-auto flex-1">
                    {selectedActivity ? (
                      isLoadingFiles ? (
                        <div className="flex items-center justify-center h-full">
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span className="ml-2 text-xs">파일 로딩 중...</span>
                        </div>
                      ) : activityFiles.length > 0 ? (
                        <Table>
                          <TableHeader className="sticky top-0 bg-background">
                            <TableRow>
                              <TableHead className="min-w-[200px] text-xs h-8">파일명</TableHead>
                              <TableHead className="w-[90px] text-xs h-8">크기</TableHead>
                              <TableHead className="w-[100px] text-xs h-8">날짜</TableHead>
                              <TableHead className="w-[90px] text-xs h-8">다운로드</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {activityFiles.map((file) => (
                              <TableRow key={file.FILE_SEQ} className="h-8">
                                <TableCell className="font-medium text-xs py-1">
                                  {file.FILE_NM}
                                </TableCell>
                                <TableCell className="text-xs text-muted-foreground py-1">
                                  {file.FILE_SZ ? formatFileSize(file.FILE_SZ) : "-"}
                                </TableCell>
                                <TableCell className="text-xs text-muted-foreground py-1">
                                  {file.CRTE_DTM ? formatSwpDateShort(file.CRTE_DTM) : "-"}
                                </TableCell>
                                <TableCell className="py-1">
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    className="h-6 px-2 text-[10px]"
                                    onClick={() => handleDownloadFile(file.FILE_NM, document.OWN_DOC_NO || document.DOC_NO)}
                                  >
                                    <Download className="h-3 w-3 mr-1" />
                                    다운로드
                                  </Button>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      ) : (
                        <div className="flex items-center justify-center h-full text-xs text-muted-foreground">
                          <div className="text-center">
                            <AlertCircle className="h-6 w-6 mx-auto mb-1 opacity-50" />
                            <p>파일이 없습니다</p>
                          </div>
                        </div>
                      )
                    ) : (
                      <div className="flex items-center justify-center h-full text-xs text-muted-foreground">
                        <div className="text-center">
                          <FileIcon className="h-8 w-8 mx-auto mb-1 opacity-30" />
                          <p>Activity를 선택해주세요</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </>
            ) : (
              <div className="p-8 text-center text-muted-foreground">
                <AlertCircle className="h-10 w-10 mx-auto mb-2 opacity-50" />
                <p className="text-sm">Activity 정보가 없습니다</p>
              </div>
            )}
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
