"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";

export interface ParsedFileInfo {
  drawingNo: string;
  revNo: string;
  fileName: string;
}

export interface FileValidationResult {
  file: File;
  valid: boolean;
  parsed?: ParsedFileInfo;
  error?: string;
  mappingStatus?: "available" | "not_found";
  drawingName?: string;
  registerGroupId?: number;
}

interface B4UploadValidationDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  validationResults: FileValidationResult[];
  onConfirmUpload: (validFiles: FileValidationResult[]) => void;
  isUploading: boolean;
}

/**
 * B4 file name validation function
 * Format: [ignore] [document_number_token1] [document_number_token2] ... [revision_number].[extension]
 * Example: "testfile GTT DE 007 R01.pdf" → DrawingNo: "GTT-DE-007", RevNo: "R01"
 * - First token is ignored
 * - Last token is RevNo
 * - Middle tokens are joined with "-" to create DrawingNo
 */
export function validateB4FileName(fileName: string): {
  valid: boolean;
  parsed?: ParsedFileInfo;
  error?: string;
} {
  try {
    // Separate extension
    const lastDotIndex = fileName.lastIndexOf(".");
    if (lastDotIndex === -1) {
      return {
        valid: false,
        error: "File has no extension",
      };
    }

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

    // Split by spaces
    const parts = nameWithoutExt.split(" ").filter(p => p.trim() !== "");

    // At least 3 parts required: [ignore], [document_number_token], [RevNo]
    if (parts.length < 3) {
      return {
        valid: false,
        error: `At least 2 spaces required (current: ${parts.length - 1}). Format: [ignore] [document_tokens...] [RevNo].[extension]`,
      };
    }

    // First token is ignored
    // Last token is RevNo
    // Middle tokens are joined with "-" to create DrawingNo
    const revNo = parts[parts.length - 1];
    const drawingTokens = parts.slice(1, parts.length - 1);
    const drawingNo = drawingTokens.join("-");

    // Check that required fields are not empty
    if (!drawingNo || drawingNo.trim() === "") {
      return {
        valid: false,
        error: "Drawing number (DrawingNo) is empty",
      };
    }

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

    return {
      valid: true,
      parsed: {
        drawingNo: drawingNo.trim(),
        revNo: revNo.trim(),
        fileName: fileName,
      },
    };
  } catch (error) {
    return {
      valid: false,
      error: error instanceof Error ? error.message : "Unknown error",
    };
  }
}

/**
 * B4 file validation dialog before upload
 */
export function B4UploadValidationDialog({
  open,
  onOpenChange,
  validationResults,
  onConfirmUpload,
  isUploading,
}: B4UploadValidationDialogProps) {
  const validFiles = validationResults.filter((r) => r.valid && r.mappingStatus === "available");
  const notFoundFiles = validationResults.filter((r) => r.valid && r.mappingStatus === "not_found");
  const invalidFiles = validationResults.filter((r) => !r.valid);

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

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[85vh] flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>B4 Bulk Upload Validation</DialogTitle>
          <DialogDescription>
            Validates file name format and mapping availability for selected files
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 overflow-auto flex-1 pr-2">
          {/* Summary statistics */}
          <div className="grid grid-cols-4 gap-3">
            <div className="rounded-lg border p-3">
              <div className="text-sm text-muted-foreground">Total</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">Ready to Upload</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-orange-50 dark:bg-orange-950/30">
              <div className="text-sm text-orange-600 dark:text-orange-400">Drawing Not Found</div>
              <div className="text-2xl font-bold text-orange-600 dark:text-orange-400">
                {notFoundFiles.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">Format Error</div>
              <div className="text-2xl font-bold text-red-600 dark:text-red-400">
                {invalidFiles.length}
              </div>
            </div>
          </div>

          {/* Warning messages */}
          {validFiles.length === 0 && (
            <Alert variant="destructive">
              <XCircle className="h-4 w-4" />
              <AlertDescription>
                No files available for upload. Please check the file name format or exclude already mapped files.
              </AlertDescription>
            </Alert>
          )}

          {(notFoundFiles.length > 0 || invalidFiles.length > 0) && validFiles.length > 0 && (
            <Alert>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                Some files have issues. Only {validFiles.length} file(s) will be uploaded.
              </AlertDescription>
            </Alert>
          )}

          {/* File list */}
          <div className="max-h-[50vh] overflow-auto rounded-md border p-4">
            <div className="space-y-4">
              {/* Files ready to upload */}
              {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" />
                    Ready to Upload ({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">
                                Drawing: {result.parsed.drawingNo}
                              </Badge>
                              <Badge variant="outline" className="text-xs">
                                Rev: {result.parsed.revNo}
                              </Badge>
                              {result.drawingName && (
                                <Badge variant="outline" className="text-xs">
                                  {result.drawingName}
                                </Badge>
                              )}
                            </div>
                          )}
                        </div>
                        <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-400 shrink-0" />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Files with drawing not found */}
              {notFoundFiles.length > 0 && (
                <div className="space-y-2 mt-4">
                  <h4 className="text-sm font-semibold text-orange-600 dark:text-orange-400 flex items-center gap-2">
                    <XCircle className="h-4 w-4" />
                    Drawing Not Found ({notFoundFiles.length})
                  </h4>
                  {notFoundFiles.map((result, index) => (
                    <div
                      key={index}
                      className="rounded-lg border border-orange-200 dark:border-orange-800 bg-orange-50 dark:bg-orange-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>
                          <div className="text-xs text-orange-700 dark:text-orange-300 mt-1">
                            ✗ This drawing number is not registered in the project
                          </div>
                          {result.parsed && (
                            <div className="flex flex-wrap gap-1 mt-2">
                              <Badge variant="outline" className="text-xs">
                                Drawing: {result.parsed.drawingNo}
                              </Badge>
                              <Badge variant="outline" className="text-xs">
                                Rev: {result.parsed.revNo}
                              </Badge>
                            </div>
                          )}
                        </div>
                        <XCircle className="h-5 w-5 text-orange-600 dark:text-orange-400 shrink-0" />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Files with format errors */}
              {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" />
                    File Name Format Error ({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>

          {/* Format guide */}
          <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">
              [fileName(without blanks)] [document_token1] [document_token2] ... [RevNo].[extension]
            </code>
            <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
              Example: testfile GTT DE 007 R01.pdf → DrawingNo: GTT-DE-007, Rev: R01
            </div>
            <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
              ※ The last word is the revision number (RevNo)
            </div>
            <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
              ※ All middle words are connected with &quot;-&quot; to become the document number (DrawingNo)
            </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>
  );
}

