"use client";

import { useState, useTransition, useMemo, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Label } from "@/components/ui/label";
import { Search, X, Check, ChevronsUpDown, Upload, RefreshCw } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { cn } from "@/lib/utils";
import { SwpUploadHelpDialog } from "./swp-help-dialog";
import { SwpUploadResultDialog } from "./swp-upload-result-dialog";
import { 
  SwpUploadValidationDialog, 
  validateFileName 
} from "./swp-upload-validation-dialog";
// import { SwpUploadedFilesDialog } from "./swp-uploaded-files-dialog";
import { getDocumentClassInfoByProjectCode } from "@/lib/swp/swp-upload-server-actions";
import type { DocumentListItem } from "@/lib/swp/document-service";

interface SwpTableFilters {
  docNo?: string;
  docTitle?: string;
  pkgNo?: string;
  stage?: string;
  status?: string;
}

interface SwpTableToolbarProps {
  projNo: string;
  filters: SwpTableFilters;
  onProjNoChange: (projNo: string) => void;
  onFiltersChange: (filters: SwpTableFilters) => void;
  onRefresh: () => void;
  onUploadComplete?: () => void; // 업로드 완료 시 콜백 (탭 전환용)
  isRefreshing: boolean;
  projects?: Array<{ PROJ_NO: string; PROJ_NM: string | null }>;
  vendorCode?: string;
  droppedFiles?: File[];
  onFilesProcessed?: () => void;
  documents?: DocumentListItem[]; // 업로드 권한 검증 + DOC_CLS (Document Class) 확인용 문서 목록
  userId?: string; // 파일 취소 시 필요
  requiredDocs?: Array<{ vendorDocNumber: string; title: string; buyerSystemComment: string | null }>; // DB Completed 상태 업로드 필요 문서
}

export function SwpTableToolbar({
  projNo,
  filters,
  onProjNoChange,
  onFiltersChange,
  onRefresh,
  onUploadComplete,
  isRefreshing,
  projects = [],
  vendorCode,
  droppedFiles = [],
  onFilesProcessed,
  documents = [],
  userId,
  requiredDocs = [],
}: SwpTableToolbarProps) {
  const [isUploading, startUpload] = useTransition();
  const [localFilters, setLocalFilters] = useState(filters);
  const { toast } = useToast();
  const [projectSearchOpen, setProjectSearchOpen] = useState(false);
  const [projectSearch, setProjectSearch] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploadResults, setUploadResults] = useState<Array<{ fileName: string; success: boolean; error?: string }>>([]);
  const [showResultDialog, setShowResultDialog] = useState(false);
  
  // 검증 다이얼로그 상태
  const [validationResults, setValidationResults] = useState<Array<{
    file: File;
    valid: boolean;
    parsed?: {
      ownDocNo: string;
      revNo: string;
      stage: string;
      fileName: string;
      extension: string;
    };
    error?: string;
  }>>([]);
  const [showValidationDialog, setShowValidationDialog] = useState(false);

  // EVCP DB에서 조회한 문서 정보 (vendorDocNumber → Document Class 매핑)
  const [vendorDocNumberToDocClassMap, setVendorDocNumberToDocClassMap] = useState<Record<string, string>>({});
  // Document Class별 허용 Stage 목록
  const [documentClassStages, setDocumentClassStages] = useState<Record<string, string[]>>({});

  /**
   * 업로드 가능한 문서번호 목록 추출 (OWN_DOC_NO 기준)
   * SWP API의 OWN_DOC_NO가 EVCP DB의 vendorDocNumber와 매핑되는지 확인
   * + DB Completed 상태 문서(requiredDocs)의 vendorDocNumber도 포함
   */
  const availableDocNos = useMemo(() => {
    // 1. documents의 OWN_DOC_NO (EVCP DB에 등록된 것만)
    const fromDocuments = documents
      .map(doc => doc.OWN_DOC_NO)
      .filter((ownDocNo): ownDocNo is string => {
        // OWN_DOC_NO가 있고, EVCP DB에 등록된 문서인지 확인
        return ownDocNo !== null && 
               ownDocNo !== undefined && 
               vendorDocNumberToDocClassMap[ownDocNo] !== undefined;
      });
    
    // 2. requiredDocs의 vendorDocNumber (DB Completed 상태)
    const fromRequiredDocs = requiredDocs
      .map(doc => doc.vendorDocNumber)
      .filter((vendorDocNumber): vendorDocNumber is string => {
        return vendorDocNumber !== null && vendorDocNumber !== undefined;
      });
    
    // 3. 중복 제거하여 병합
    return Array.from(new Set([...fromDocuments, ...fromRequiredDocs]));
  }, [documents, requiredDocs, vendorDocNumberToDocClassMap]);

  /**
   * 벤더 모드 여부 (벤더 코드가 있으면 벤더 모드)
   */
  const isVendorMode = !!vendorCode;

  /**
   * 프로젝트 변경 시 EVCP DB에서 문서 정보 로드
   * - vendorDocNumber → docClass 매핑
   * - Document Class별 허용 Stage 목록
   */
  useEffect(() => {
    if (!projNo) {
      setVendorDocNumberToDocClassMap({});
      setDocumentClassStages({});
      return;
    }

    let isCancelled = false;

    const loadDocumentClassInfo = async () => {
      try {
        console.log(`[SwpTableToolbar] Start loading document info for project ${projNo}`);

        // 서버 액션 호출
        const result = await getDocumentClassInfoByProjectCode(projNo);
        
        if (!isCancelled) {
          if (result.success) {
            setVendorDocNumberToDocClassMap(result.vendorDocNumberToDocClassMap);
            setDocumentClassStages(result.documentClassStages);
            
            console.log(`[SwpTableToolbar] Document info load complete:`, {
              vendorDocNumbers: Object.keys(result.vendorDocNumberToDocClassMap).length,
              documentClassStages: result.documentClassStages,
            });
          } else {
            console.warn(`[SwpTableToolbar] Document info load failed:`, result.error);
            setVendorDocNumberToDocClassMap({});
            setDocumentClassStages({});
            
            toast({
              variant: "destructive",
              title: "Failed to load document info",
              description: result.error || "Cannot retrieve document info.",
            });
          }
        }
      } catch (error) {
        if (!isCancelled) {
          console.error('[SwpTableToolbar] Failed to load document info:', error);
          setVendorDocNumberToDocClassMap({});
          setDocumentClassStages({});
          
          toast({
            variant: "destructive",
            title: "Failed to load document info",
            description: "Cannot retrieve document info. Please refresh the page.",
          });
        }
      }
    };

    loadDocumentClassInfo();

    return () => {
      isCancelled = true;
    };
  }, [projNo, toast]);

  /**
   * 드롭된 파일 처리 - useEffect로 감지하여 자동 검증
   */
  useEffect(() => {
    if (droppedFiles.length > 0) {
      // 프로젝트와 벤더 코드 검증
      if (!projNo) {
        toast({
          variant: "destructive",
          title: "Project selection required",
          description: "Please select a project to upload files to first.",
        });
        onFilesProcessed?.();
        return;
      }

      if (!vendorCode) {
        toast({
          variant: "destructive",
          title: "Vendor code error",
          description: "Cannot retrieve vendor info.",
        });
        onFilesProcessed?.();
        return;
      }

      // 파일명 검증 (문서번호 권한 + Stage 검증 포함)
      const results = droppedFiles.map((file) => {
        const validation = validateFileName(
          file.name,
          availableDocNos,
          isVendorMode,
          vendorDocNumberToDocClassMap,
          documentClassStages
        );
        return {
          file,
          valid: validation.valid,
          parsed: validation.parsed,
          error: validation.error,
        };
      });

      setValidationResults(results);
      setShowValidationDialog(true);
      onFilesProcessed?.();
    }
  }, [droppedFiles, projNo, vendorCode, toast, onFilesProcessed, availableDocNos, isVendorMode, vendorDocNumberToDocClassMap, documentClassStages]);

  /**
   * 파일 업로드 핸들러
   */
  const handleUploadFiles = () => {
    if (!projNo) {
      toast({
        variant: "destructive",
        title: "Project selection required",
        description: "Please select a project to upload files to first.",
      });
      return;
    }

    if (!vendorCode) {
      toast({
        variant: "destructive",
        title: "Vendor code error",
        description: "Cannot retrieve vendor info.",
      });
      return;
    }

    fileInputRef.current?.click();
  };

  /**
   * 파일 선택 핸들러 - 검증만 수행
   */
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = event.target.files;
    if (!selectedFiles || selectedFiles.length === 0) {
      return;
    }

    // 각 파일의 파일명 검증 (문서번호 권한 + Stage 검증 포함)
    const results = Array.from(selectedFiles).map((file) => {
      const validation = validateFileName(
        file.name,
        availableDocNos,
        isVendorMode,
        vendorDocNumberToDocClassMap,
        documentClassStages
      );
      return {
        file,
        valid: validation.valid,
        parsed: validation.parsed,
        error: validation.error,
      };
    });

    setValidationResults(results);
    setShowValidationDialog(true);

    // input 초기화 (같은 파일 재선택 가능하도록)
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  /**
   * 검증 완료 후 실제 업로드 실행
   */
  const handleConfirmUpload = async (validFiles: File[]) => {
    startUpload(async () => {
      try {
        toast({
          title: "File upload started",
          description: `Uploading ${validFiles.length} files...`,
        });

        const formData = new FormData();
        formData.append("projNo", projNo);
        formData.append("vndrCd", vendorCode!);

        validFiles.forEach((file) => {
          formData.append("files", file);
        });

        const response = await fetch("/api/swp/upload", {
          method: "POST",
          body: formData,
        });

        if (!response.ok) {
          throw new Error(`Upload failed: ${response.statusText}`);
        }

        const result = await response.json();

        // 검증 다이얼로그 닫기
        setShowValidationDialog(false);

        // 결과 다이얼로그 표시
        setUploadResults(result.details || []);
        setShowResultDialog(true);

        toast({
          title: result.success ? "Upload complete" : "Some uploads failed",
          description: result.message,
        });

        // 업로드 성공 시 자동 새로고침 (외부 시스템 처리 시간 고려)
        if (result.success && result.successCount > 0) {
          // 업로드 완료 시 Inbox 탭으로 전환
          onUploadComplete?.();
          
          toast({
            title: "Refreshing document list",
            description: "Waiting for external system processing...",
          });
          
          // 2초 딜레이 후 새로고침
          setTimeout(() => {
            onRefresh();
            toast({
              title: "Refresh complete",
              description: "Uploaded files have been reflected in the document list.",
            });
          }, 2000);
        }
      } catch (error) {
        console.error("File upload failed:", error);

        // 검증 다이얼로그 닫기
        setShowValidationDialog(false);

        const errorResults = validFiles.map((file) => ({
          fileName: file.name,
          success: false,
          error: error instanceof Error ? error.message : "Unknown error",
        }));

        setUploadResults(errorResults);
        setShowResultDialog(true);
      }
    });
  };

  // 검색 적용
  const handleSearch = () => {
    onFiltersChange(localFilters);
  };

  // 검색 초기화
  const handleReset = () => {
    const resetFilters: SwpTableFilters = {
      docNo: "",
      docTitle: "",
      pkgNo: "",
      stage: "",
    };
    setLocalFilters(resetFilters);
    onFiltersChange(resetFilters);
  };

  // 프로젝트 필터링
  const filteredProjects = useMemo(() => {
    if (!projectSearch) return projects;

    const search = projectSearch.toLowerCase();
    return projects.filter(
      (proj) =>
        proj.PROJ_NO.toLowerCase().includes(search) ||
        (proj.PROJ_NM?.toLowerCase().includes(search) ?? false)
    );
  }, [projects, projectSearch]);

  return (
    <>
      {/* 업로드 검증 다이얼로그 */}
      <SwpUploadValidationDialog
        open={showValidationDialog}
        onOpenChange={setShowValidationDialog}
        validationResults={validationResults}
        onConfirmUpload={handleConfirmUpload}
        isUploading={isUploading}
        availableDocNos={availableDocNos}
        isVendorMode={isVendorMode}
      />

      {/* 업로드 결과 다이얼로그 */}
      <SwpUploadResultDialog
        open={showResultDialog}
        onOpenChange={setShowResultDialog}
        results={uploadResults}
      />

      <div className="space-y-4 w-full">
        {/* 상단 액션 바 */}
        {vendorCode && (
          <div className="flex items-center justify-end gap-2">
            <input
              ref={fileInputRef}
              type="file"
              multiple
              className="hidden"
              onChange={handleFileChange}
              accept="*/*"
            />
            <Button
              variant="outline"
              size="sm"
              onClick={onRefresh}
              disabled={isRefreshing || !projNo}
            >
              <RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`} />
              Refresh
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleUploadFiles}
              disabled={isUploading || !projNo}
            >
              <Upload className={`h-4 w-4 mr-2 ${isUploading ? "animate-pulse" : ""}`} />
              {isUploading ? "Uploading..." : "Upload File"}
            </Button>

            {/* 별도 탭으로 분리하고 메인 테이블로 변경하였음. */}
            {/* {userId && (
              <SwpUploadedFilesDialog
                projNo={projNo}
                vndrCd={vendorCode}
                userId={userId}
              />
            )} */}

            <SwpUploadHelpDialog />
          </div>
        )}

        {/* 검색 필터 */}
        <div className="rounded-lg border p-4 space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-semibold">Search Filter</h3>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleReset}
              className="h-8"
              disabled={isRefreshing}
            >
              <X className="h-4 w-4 mr-1" />
              Reset
            </Button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {/* 프로젝트 번호 */}
            <div className="space-y-2">
              <Label htmlFor="projNo">Project Number</Label>
              {projects.length > 0 ? (
                <Popover open={projectSearchOpen} onOpenChange={setProjectSearchOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      aria-expanded={projectSearchOpen}
                      className="w-full justify-between"
                      disabled={isRefreshing}
                    >
                      {projNo ? (
                        <span>
                          {projects.find((p) => p.PROJ_NO === projNo)?.PROJ_NO || projNo}
                          {" ["}
                          {projects.find((p) => p.PROJ_NO === projNo)?.PROJ_NM}
                          {"]"}
                        </span>
                      ) : (
                        <span className="text-muted-foreground">Select Project</span>
                      )}
                      <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-[400px] p-0" align="start">
                    <div className="p-2">
                      <div className="flex items-center border rounded-md px-3">
                        <Search className="h-4 w-4 mr-2 opacity-50" />
                        <Input
                          placeholder="Search by project number or name..."
                          value={projectSearch}
                          onChange={(e) => setProjectSearch(e.target.value)}
                          className="border-0 focus-visible:ring-0 focus-visible:ring-offset-0"
                        />
                      </div>
                    </div>
                    <div className="max-h-[300px] overflow-y-auto">
                      <div className="p-1">
                        {filteredProjects.map((proj) => (
                          <Button
                            key={proj.PROJ_NO}
                            variant="ghost"
                            className="w-full justify-start font-normal"
                            onClick={() => {
                              onProjNoChange(proj.PROJ_NO);
                              setProjectSearchOpen(false);
                              setProjectSearch("");
                            }}
                          >
                            <Check
                              className={cn(
                                "mr-2 h-4 w-4",
                                projNo === proj.PROJ_NO ? "opacity-100" : "opacity-0"
                              )}
                            />
                            <span className="font-mono text-sm">{proj.PROJ_NO} [{proj.PROJ_NM || ""}]</span>
                          </Button>
                        ))}
                        {filteredProjects.length === 0 && (
                          <div className="py-6 text-center text-sm text-muted-foreground">
                            No search results.
                          </div>
                        )}
                      </div>
                    </div>
                  </PopoverContent>
                </Popover>
              ) : (
                <Input
                  id="projNo"
                  placeholder="No contracted projects"
                  value={projNo}
                  disabled
                  className="bg-muted"
                />
              )}
            </div>

            {/* 문서 번호 */}
            <div className="space-y-2">
              <Label htmlFor="docNo">Document Number</Label>
              <Input
                id="docNo"
                placeholder="Search Document Number"
                value={localFilters.docNo || ""}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, docNo: e.target.value })
                }
                disabled={isRefreshing}
              />
            </div>

            {/* 문서 제목 */}
            <div className="space-y-2">
              <Label htmlFor="docTitle">Document Title</Label>
              <Input
                id="docTitle"
                placeholder="Search Title"
                value={localFilters.docTitle || ""}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, docTitle: e.target.value })
                }
                disabled={isRefreshing}
              />
            </div>

            {/* 패키지 번호 */}
            <div className="space-y-2">
              <Label htmlFor="pkgNo">Package</Label>
              <Input
                id="pkgNo"
                placeholder="Package Number"
                value={localFilters.pkgNo || ""}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, pkgNo: e.target.value })
                }
                disabled={isRefreshing}
              />
            </div>

            {/* 스테이지 */}
            <div className="space-y-2">
              <Label htmlFor="stage">Stage</Label>
              <Input
                id="stage"
                placeholder="Enter Stage (e.g. IFC, IFA)"
                value={localFilters.stage || ""}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, stage: e.target.value })
                }
                disabled={isRefreshing}
              />
            </div>

            {/* 상태 */}
            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Input
                id="status"
                placeholder="ex. standby.."
                value={localFilters.status || ""}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, status: e.target.value })
                }
                disabled={isRefreshing}
              />
            </div>
          </div>

          <div className="flex justify-end">
            <Button 
              onClick={handleSearch} 
              size="sm"
              disabled={isRefreshing}
            >
              <Search className={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`} />
              {isRefreshing ? "Loading..." : "Search"}
            </Button>
          </div>
        </div>
      </div>
    </>
  );
}
