"use client";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { CheckCircle2, XCircle, AlertCircle, Upload } from "lucide-react";

interface FileValidationResult {
  file: File;
  valid: boolean;
  parsed?: {
    ownDocNo: string;
    revNo: string;
    stage: string;
    fileName: string;
    extension: string;
  };
  error?: string;
}

interface SwpUploadValidationDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  validationResults: FileValidationResult[];
  onConfirmUpload: (validFiles: File[]) => void;
  isUploading: boolean;
  availableDocNos?: string[]; // 업로드 가능한 문서번호 목록
  isVendorMode?: boolean; // 벤더 모드인지 여부 (문서번호 검증 필수)
}

/**
 * 파일명 검증 함수 (클라이언트 사이드)
 * 형식: [OWN_DOC_NO]_[REV_NO]_[STAGE].[확장자] 또는 [OWN_DOC_NO]_[REV_NO]_[STAGE]_[자유-파일명].[확장자]
 * 자유 파일명은 선택사항이며, 포함될 경우 언더스코어를 포함할 수 있음
 * @param fileName 검증할 파일명
 * @param availableDocNos 업로드 가능한 문서번호 목록 (선택)
 * @param isVendorMode 벤더 모드인지 여부 (true인 경우 문서번호 검증 필수)
 * @param docNoToDocClsMap 문서번호 → DOC_CLS (Document Class) 매핑 (Stage 검증용)
 * @param documentClassStages Document Class → 허용 Stage 목록 매핑
 */
export function validateFileName(
  fileName: string,
  availableDocNos?: string[],
  isVendorMode?: boolean,
  docNoToDocClsMap?: Record<string, string>,
  documentClassStages?: Record<string, string[]>
): {
  valid: boolean;
  parsed?: {
    ownDocNo: string;
    revNo: string;
    stage: string;
    fileName: string;
    extension: string;
  };
  error?: string;
} {
  try {
    // 확장자 분리
    const lastDotIndex = fileName.lastIndexOf(".");
    if (lastDotIndex === -1) {
      return {
        valid: false,
        error: "File extension missing",
      };
    }

    const extension = fileName.substring(lastDotIndex + 1);
    const nameWithoutExt = fileName.substring(0, lastDotIndex);

    // 언더스코어로 분리
    const parts = nameWithoutExt.split("_");

    // 최소 3개 파트 필요: ownDocNo, revNo, stage (fileName은 선택사항)
    if (parts.length < 3) {
      return {
        valid: false,
        error: `Must have at least 2 underscores (_) (Current: ${parts.length - 1}). Format: [OWN_DOC_NO]_[REV_NO]_[STAGE].[Extension]`,
      };
    }

    // 앞에서부터 3개는 고정: ownDocNo, revNo, stage
    const ownDocNo = parts[0];
    const revNo = parts[1];
    const stage = parts[2];
    
    // 나머지는 자유 파일명 (선택사항, 언더스코어 포함 가능)
    const customFileName = parts.length > 3 ? parts.slice(3).join("_") : "";

    // 필수 항목이 비어있지 않은지 확인
    if (!ownDocNo || ownDocNo.trim() === "") {
      return {
        valid: false,
        error: "Document Number (OWN_DOC_NO) is empty",
      };
    }

    if (!revNo || revNo.trim() === "") {
      return {
        valid: false,
        error: "Revision Number (REV_NO) is empty",
      };
    }

    if (!stage || stage.trim() === "") {
      return {
        valid: false,
        error: "Stage (STAGE) is empty",
      };
    }

    // trim된 값 미리 준비 (중복 제거)
    const trimmedDocNo = ownDocNo.trim();
    const trimmedStage = stage.trim();

    // 문서번호 검증 (벤더 모드에서는 필수)
    if (isVendorMode) {
      // 벤더 모드에서 문서 목록이 비어있으면 에러
      if (!availableDocNos || availableDocNos.length === 0) {
        return {
          valid: false,
          error: "No assigned documents or failed to load document list. Please refresh the page or contact administrator.",
        };
      }
      
      // 문서번호가 목록에 없으면 에러
      if (!availableDocNos.includes(trimmedDocNo)) {
        return {
          valid: false,
          error: `Document number '${trimmedDocNo}' does not have upload permission. Please check assigned document numbers.`,
        };
      }
    }

    // Stage 검증 (Document Class별 허용 Stage 확인)
    // EVCP DB에서 vendorDocNumber로 Document Class를 조회하고,
    // 해당 Document Class의 허용 Stage 목록과 비교

    if (docNoToDocClsMap && documentClassStages) {
      const docCls = docNoToDocClsMap[trimmedDocNo];
      console.log(`[validateFileName] 문서 '${trimmedDocNo}' → Document Class: '${docCls || "null"}'`);
      
      if (!docCls) {
        // 문서가 EVCP DB에 등록되지 않음
        return {
          valid: false,
          error: `Document number '${trimmedDocNo}' is not registered in the document list. Please submit the document list first.`,
        };
      }

      const allowedStages = documentClassStages[docCls];
      console.log(`[validateFileName] Document Class '${docCls}' → 허용 Stage:`, allowedStages);
      
      if (!allowedStages || allowedStages.length === 0) {
        // Document Class에 Stage가 설정되지 않음
        return {
          valid: false,
          error: `Stage is not set for Document Class '${docCls}' of document '${trimmedDocNo}'. Please contact administrator.`,
        };
      }

      console.log(`[validateFileName] Stage 검증: '${trimmedStage}' in [${allowedStages.join(", ")}]`);
      if (!allowedStages.includes(trimmedStage)) {
        return {
          valid: false,
          error: `Stage '${trimmedStage}' is not allowed for Document Class '${docCls}' of document '${trimmedDocNo}'. Allowed Stages: ${allowedStages.join(", ")}`,
        };
      }
      
      console.log(`[validateFileName] Stage 검증 통과: '${trimmedStage}'`);
    } else {
      // 검증 정보가 로드되지 않음
      console.log(`[validateFileName] 검증 정보가 없음 → 업로드 차단`);
      return {
        valid: false,
        error: "Cannot retrieve document info. Please refresh the page or re-select the project.",
      };
    }

    return {
      valid: true,
      parsed: {
        ownDocNo: trimmedDocNo,
        revNo: revNo.trim(),
        stage: trimmedStage,
        fileName: customFileName.trim(),
        extension,
      },
    };
  } catch (error) {
    return {
      valid: false,
      error: error instanceof Error ? error.message : "Unknown error",
    };
  }
}

/**
 * 업로드 전 파일 검증 다이얼로그
 */
export function SwpUploadValidationDialog({
  open,
  onOpenChange,
  validationResults,
  onConfirmUpload,
  isUploading,
  availableDocNos = [],
  isVendorMode = false,
}: SwpUploadValidationDialogProps) {
  const validFiles = validationResults.filter((r) => r.valid);
  const invalidFiles = validationResults.filter((r) => !r.valid);

  const handleUpload = () => {
    if (validFiles.length > 0) {
      onConfirmUpload(validFiles.map((r) => r.file));
    }
  };

  const handleCancel = () => {
    if (!isUploading) {
      onOpenChange(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[80vh] flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>File Upload Validation</DialogTitle>
          <DialogDescription>
            Validating file name format of selected files
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 overflow-auto flex-1 pr-2">
          {/* 요약 통계 */}
          <div className="grid grid-cols-3 gap-4">
            <div className="rounded-lg border p-3">
              <div className="text-sm text-muted-foreground">Total Files</div>
              <div className="text-2xl font-bold">{validationResults.length}</div>
            </div>
            <div className="rounded-lg border p-3 bg-green-50 dark:bg-green-950/30">
              <div className="text-sm text-green-600 dark:text-green-400">Validation Success</div>
              <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                {validFiles.length}
              </div>
            </div>
            <div className="rounded-lg border p-3 bg-red-50 dark:bg-red-950/30">
              <div className="text-sm text-red-600 dark:text-red-400">Validation Failed</div>
              <div className="text-2xl font-bold text-red-600 dark:text-red-400">
                {invalidFiles.length}
              </div>
            </div>
          </div>

          {/* 경고 메시지 */}
          {invalidFiles.length > 0 && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                {invalidFiles.length} files have incorrect file name format.
                Only {validFiles.length} successfully validated files will be uploaded.
              </AlertDescription>
            </Alert>
          )}

          {validFiles.length === 0 && (
            <Alert variant="destructive">
              <XCircle className="h-4 w-4" />
              <AlertDescription>
                No uploadable files. Please check file name format.
              </AlertDescription>
            </Alert>
          )}

          {/* 파일 목록 */}
          <div className="max-h-[50vh] overflow-auto rounded-md border p-4">
            <div className="space-y-3">
              {/* 검증 성공 파일 */}
              {validFiles.length > 0 && (
                <div className="space-y-2">
                  <h4 className="text-sm font-semibold text-green-600 dark:text-green-400 flex items-center gap-2">
                    <CheckCircle2 className="h-4 w-4" />
                    Validation Success ({validFiles.length})
                  </h4>
                  {validFiles.map((result, index) => (
                    <div
                      key={index}
                      className="rounded-lg border border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-950/30 p-3"
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex-1 min-w-0">
                          <div className="font-mono text-sm break-all">
                            {result.file.name}
                          </div>
                          {result.parsed && (
                            <div className="flex flex-wrap gap-1 mt-2">
                              <Badge variant="outline" className="text-xs">
                                Doc: {result.parsed.ownDocNo}
                              </Badge>
                              <Badge variant="outline" className="text-xs">
                                Rev: {result.parsed.revNo}
                              </Badge>
                              <Badge variant="outline" className="text-xs">
                                Stage: {result.parsed.stage}
                              </Badge>
                              {result.parsed.fileName && (
                                <Badge variant="outline" className="text-xs">
                                  FileName: {result.parsed.fileName}
                                </Badge>
                              )}
                              <Badge variant="outline" className="text-xs">
                                Ext: .{result.parsed.extension}
                              </Badge>
                            </div>
                          )}
                        </div>
                        <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-400 shrink-0" />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* 검증 실패 파일 */}
              {invalidFiles.length > 0 && (
                <div className="space-y-2 mt-4">
                  <h4 className="text-sm font-semibold text-red-600 dark:text-red-400 flex items-center gap-2">
                    <XCircle className="h-4 w-4" />
                    Validation Failed ({invalidFiles.length})
                  </h4>
                  {invalidFiles.map((result, index) => (
                    <div
                      key={index}
                      className="rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/30 p-3"
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex-1 min-w-0">
                          <div className="font-mono text-sm break-all">
                            {result.file.name}
                          </div>
                          {result.error && (
                            <div className="text-xs text-red-600 dark:text-red-400 mt-1">
                              ✗ {result.error}
                            </div>
                          )}
                        </div>
                        <XCircle className="h-5 w-5 text-red-600 dark:text-red-400 shrink-0" />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* 형식 안내 */}
          <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-sm font-medium text-blue-900 dark:text-blue-100 mb-1">
              📋 Correct File Name Format
            </div>
            <code className="text-xs text-blue-700 dark:text-blue-300">
              [OWN_DOC_NO]_[REV_NO]_[STAGE].[Extension]
            </code>
            <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
              Ex: VD-DOC-001_01_IFA.pdf
            </div>
            <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
              ※ Optional: [OWN_DOC_NO]_[REV_NO]_[STAGE]_[FileName].[Extension] (FileName can be added)
            </div>
            <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
              ※ File name can contain underscores (_).
            </div>
            {isVendorMode && (
              <>
                <div className="text-xs text-blue-600 dark:text-blue-400 mt-2 pt-2 border-t border-blue-200 dark:border-blue-800">
                  {availableDocNos.length > 0 ? (
                    <>ℹ️ Uploadable Documents: {availableDocNos.length}</>
                  ) : (
                    <>⚠️ No assigned documents</>
                  )}
                </div>
                <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
                  ⚠️ Only Stages defined in each document's Document Class can be used.
                </div>
              </>
            )}
          </div>
        </div>

        <DialogFooter className="flex-shrink-0">
          <Button
            variant="outline"
            onClick={handleCancel}
            disabled={isUploading}
          >
            Cancel
          </Button>
          <Button
            onClick={handleUpload}
            disabled={validFiles.length === 0 || isUploading}
          >
            {isUploading ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                Uploading...
              </>
            ) : (
              <>
                <Upload className="h-4 w-4 mr-2" />
                Upload ({validFiles.length})
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

