"use client";

import React, { useState, useCallback } from "react";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { useBulkScanUpload } from "@/lib/api/hooks/useCertificates";
import type { BulkScanResponse } from "@/lib/api/types/certificate.types";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  refreshData?: () => void;
}

export default function BulkScanModal({ isOpen, onClose, refreshData }: Props) {
  const { upload, result, uploading, error, reset } = useBulkScanUpload();
  const [files, setFiles] = useState<File[]>([]);
  const [dragging, setDragging] = useState(false);

  const handleFiles = useCallback((fileList: FileList | null) => {
    if (!fileList) return;
    const pdfs = Array.from(fileList).filter(
      (f) => f.type === "application/pdf" || f.name.toLowerCase().endsWith(".pdf"),
    );
    if (pdfs.length < fileList.length) {
      toast("Some non-PDF files were skipped", { icon: "⚠️" });
    }
    setFiles((prev) => [...prev, ...pdfs]);
  }, []);

  const onDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
    handleFiles(e.dataTransfer.files);
  };

  const onFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    handleFiles(e.target.files);
    e.target.value = "";
  };

  const removeFile = (idx: number) => {
    setFiles((prev) => prev.filter((_, i) => i !== idx));
  };

  const handleUpload = async () => {
    if (files.length === 0) {
      toast.error("Please select at least one PDF file");
      return;
    }
    const res = await upload(files);
    if (res) {
      const matched = res.matched?.length ?? 0;
      const total = files.length;
      if (matched > 0) {
        toast.success(`${matched} of ${total} scans matched successfully`);
        refreshData?.();
      } else {
        toast.error("No scans matched — please check filenames");
      }
      setFiles([]);
    }
  };

  const handleClose = () => {
    setFiles([]);
    reset();
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className={styles.modalOverlay}>
      <div className={styles.modalContent} style={{ maxWidth: 800, width: "95%" }}>
        <div className={styles.modalHeader}>
          <h2 className={styles.modalTitle}>📤 Bulk Upload Scans</h2>
          <button
            className={styles.closeBtn}
            onClick={handleClose}
            type="button"
          >
            ×
          </button>
        </div>

        <div className={styles.formBody}>
          {/* Instructions */}
          <div className={styles.alertSuccess} style={{ marginBottom: 16 }}>
            <strong>📌 How it works:</strong> Name each PDF exactly as its cert
            number (e.g.{" "}
            <code
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                background: "#dbeafe",
                padding: "1px 6px",
                borderRadius: 3,
              }}
            >
              UAE-AB-QMS-1C33R.pdf
            </code>
            ,{" "}
            <code
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                background: "#dbeafe",
                padding: "1px 6px",
                borderRadius: 3,
              }}
            >
              UAE-A-EMS-MK347.pdf
            </code>
            ,{" "}
            <code
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                background: "#dbeafe",
                padding: "1px 6px",
                borderRadius: 3,
              }}
            >
              PA-LA-QMS-8N4T7.pdf
            </code>{" "}
            or{" "}
            <code
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                background: "#dbeafe",
                padding: "1px 6px",
                borderRadius: 3,
              }}
            >
              AAU-10133.pdf
            </code>
            ). The system extracts the cert number from the filename and
            attaches the scan to the matching certificate, flipping its status
            to <strong>active</strong>.
          </div>

          {/* Drop zone */}
          {!result && (
            <>
              <div
                onDrop={onDrop}
                onDragOver={(e) => {
                  e.preventDefault();
                  setDragging(true);
                }}
                onDragLeave={() => setDragging(false)}
                className={`${styles.fileUploadZone} ${
                  dragging ? styles.fileUploadZoneDragOver : ""
                }`}
                onClick={() =>
                  document.getElementById("bulk-scan-input")?.click()
                }
              >
                <div className={styles.fileUploadIcon}>📁</div>
                <div className={styles.fileUploadText}>
                  Drop PDF files here or click to browse
                </div>
                <div className={styles.fileUploadHint}>
                  You can upload up to 200 files at once
                </div>
                <input
                  id="bulk-scan-input"
                  type="file"
                  multiple
                  accept="application/pdf,.pdf"
                  className={styles.fileHiddenInput}
                  onChange={onFileInput}
                />
              </div>

              {/* File list */}
              {files.length > 0 && (
                <div style={{ marginTop: 16 }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      marginBottom: 8,
                    }}
                  >
                    <div
                      style={{
                        fontSize: 11,
                        fontWeight: 800,
                        color: "#94a3b8",
                        letterSpacing: ".08em",
                        textTransform: "uppercase",
                      }}
                    >
                      Selected Files ({files.length})
                    </div>
                    <button
                      onClick={() => setFiles([])}
                      style={{
                        background: "none",
                        border: "none",
                        color: "#dc2626",
                        fontSize: 12,
                        cursor: "pointer",
                        textDecoration: "underline",
                      }}
                    >
                      Clear all
                    </button>
                  </div>
                  <div className={styles.fileList}>
                    {files.map((f, i) => {
                      const inferred = inferCertNo(f.name);
                      return (
                        <div key={i} className={styles.fileItem}>
                          <div className={styles.fileItemName}>
                            <span style={{ fontSize: 14 }}>📄</span>
                            <div style={{ minWidth: 0 }}>
                              <div
                                style={{
                                  overflow: "hidden",
                                  textOverflow: "ellipsis",
                                  whiteSpace: "nowrap",
                                }}
                              >
                                {f.name}
                              </div>
                              <div
                                style={{
                                  fontSize: 10,
                                  color: inferred ? "#15803d" : "#dc2626",
                                  fontFamily: "'IBM Plex Mono', monospace",
                                  marginTop: 2,
                                }}
                              >
                                {inferred
                                  ? `→ ${inferred}`
                                  : "⚠️ No cert number pattern detected"}
                              </div>
                            </div>
                          </div>
                          <span
                            style={{
                              fontSize: 10,
                              color: "#94a3b8",
                              marginRight: 8,
                            }}
                          >
                            {(f.size / 1024).toFixed(0)} KB
                          </span>
                          <button
                            onClick={() => removeFile(i)}
                            className={styles.fileRemoveBtn}
                          >
                            Remove
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </>
          )}

          {/* Result */}
          {result && <ResultPanel result={result} />}

          {error && (
            <div className={styles.alertError} style={{ marginTop: 12 }}>
              ⚠️ {error}
            </div>
          )}
        </div>

        <div className={styles.modalFooter}>
          {!result ? (
            <>
              <button
                className={styles.btnCancel}
                onClick={handleClose}
                type="button"
              >
                Cancel
              </button>
              <button
                className={styles.btnSubmit}
                onClick={handleUpload}
                type="button"
                disabled={files.length === 0 || uploading}
                style={{
                  opacity: files.length === 0 || uploading ? 0.5 : 1,
                }}
              >
                {uploading
                  ? "Uploading..."
                  : `Upload ${files.length} file${
                      files.length === 1 ? "" : "s"
                    }`}
              </button>
            </>
          ) : (
            <button
              className={styles.btnSubmit}
              onClick={handleClose}
              type="button"
            >
              Done
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// Client-side cert number detection (for preview only — backend does the
// REAL match, including DB lookup).
//
// 🔴 IMPORTANT: These patterns MUST mirror `CERT_NUMBER_PATTERNS` in
//    backend/src/certificates/bulk-scan/bulk-scan.service.ts
//
// If you add / change a pattern in one file, change it in the other too.
//
// Covers every cert format the system can auto-generate:
//   • UAE-AB-QMS-1C33R   — 4-seg, 2-char dept (most common)
//   • UAE-A-EMS-MK347    — 4-seg, 1-char dept           ← was failing before
//   • UAE-22-001-12345   — 4-seg, numeric segments
//   • PA-LA-QMS-8N4T7    — 4-seg, non-UAE prefix         ← was failing before
//   • KSA-RD-OHA-12345   — 4-seg, any 2-4 char country
//   • UAE-AB-9878        — 3-seg manual short
//   • ADU-AB-9878        — 3-seg, any country
//   • AAU-10133          — legacy 2-seg
// ═══════════════════════════════════════════════════════════════════════════
const CERT_NUMBER_PATTERNS: RegExp[] = [
  // ── 4-SEGMENT (most specific first) ─────────────────────────
  /\bUAE-[A-Z]{2}-[A-Z]{3,5}-[A-Z0-9]{4,6}(?:\.\d+)?\b/i,
  /\bUAE-[A-Z0-9]{1,5}-[A-Z0-9]{1,5}-[A-Z0-9]{3,8}(?:\.\d+)?\b/i,
  /\b[A-Z]{2,4}-[A-Z0-9]{1,5}-[A-Z0-9]{1,5}-[A-Z0-9]{3,8}(?:\.\d+)?\b/i,
  // ── 3-SEGMENT ────────────────────────────────────────────────
  /\b[A-Z]{2,4}-[A-Z0-9]{1,5}-[A-Z0-9]{3,8}(?:\.\d+)?\b/i,
  // ── LEGACY 2-SEGMENT ─────────────────────────────────────────
  /\b[A-Z]{3,4}-\d{4,6}(?:\.\d+)?\b/i,
];

function inferCertNo(filename: string): string | null {
  // Normalize: strip extension and Windows/macOS duplicate suffixes
  const name = filename
    .replace(/\.pdf$/i, "")
    .replace(/\s*\(\d+\)\s*$/, "")    // " (1)", " (2)"
    .replace(/\s*-\s*copy\s*$/i, "")  // " - Copy"
    .replace(/\s*copy\s*$/i, "")      // " copy"
    .trim();

  for (const p of CERT_NUMBER_PATTERNS) {
    const m = name.match(p);
    if (m) return m[0].toUpperCase();
  }
  return null;
}

function ResultPanel({ result }: { result: BulkScanResponse }) {
  const { matched = [], review = [], unmatched = [] } = result;

  return (
    <div>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(3,1fr)",
          gap: 10,
          marginBottom: 16,
        }}
      >
        <StatCard
          label="Matched"
          count={matched.length}
          color="#15803d"
          bg="#dcfce7"
          icon="✅"
        />
        <StatCard
          label="Review"
          count={review.length}
          color="#b45309"
          bg="#fef3c7"
          icon="👀"
        />
        <StatCard
          label="Unmatched"
          count={unmatched.length}
          color="#991b1b"
          bg="#fef2f2"
          icon="❌"
        />
      </div>

      {matched.length > 0 && (
        <ListSection title="Successfully matched" color="#15803d">
          {matched.map((m, i) => (
            <ListItem
              key={i}
              filename={m.filename}
              certNo={m.certificate_no}
              note={`Certificate #${m.certificate_id} is now active`}
              color="#15803d"
            />
          ))}
        </ListSection>
      )}

      {review.length > 0 && (
        <ListSection title="Need review" color="#b45309">
          {review.map((m, i) => (
            <ListItem
              key={i}
              filename={m.filename}
              certNo={m.certificate_no}
              note={m.reason}
              color="#b45309"
            />
          ))}
        </ListSection>
      )}

      {unmatched.length > 0 && (
        <ListSection title="Unmatched" color="#991b1b">
          {unmatched.map((m, i) => (
            <ListItem
              key={i}
              filename={m.filename}
              certNo={null}
              note={m.reason}
              color="#991b1b"
            />
          ))}
        </ListSection>
      )}
    </div>
  );
}

function StatCard({
  label,
  count,
  color,
  bg,
  icon,
}: {
  label: string;
  count: number;
  color: string;
  bg: string;
  icon: string;
}) {
  return (
    <div
      style={{
        padding: 14,
        background: bg,
        borderRadius: 8,
        textAlign: "center",
      }}
    >
      <div style={{ fontSize: 22, marginBottom: 2 }}>{icon}</div>
      <div style={{ fontSize: 24, fontWeight: 800, color, lineHeight: 1 }}>
        {count}
      </div>
      <div
        style={{
          fontSize: 11,
          color,
          marginTop: 4,
          fontWeight: 700,
          letterSpacing: ".04em",
          textTransform: "uppercase",
        }}
      >
        {label}
      </div>
    </div>
  );
}

function ListSection({
  title,
  color,
  children,
}: {
  title: string;
  color: string;
  children: React.ReactNode;
}) {
  return (
    <div style={{ marginTop: 12 }}>
      <div
        style={{
          fontSize: 11,
          fontWeight: 800,
          color,
          letterSpacing: ".08em",
          textTransform: "uppercase",
          marginBottom: 6,
        }}
      >
        {title}
      </div>
      <div
        style={{
          border: "1px solid #e2e8f0",
          borderRadius: 6,
          maxHeight: 200,
          overflow: "auto",
        }}
      >
        {children}
      </div>
    </div>
  );
}

function ListItem({
  filename,
  certNo,
  note,
  color,
}: {
  filename: string;
  certNo: string | null;
  note: string;
  color: string;
}) {
  return (
    <div
      style={{
        padding: "8px 12px",
        borderBottom: "1px solid #f1f5f9",
        display: "flex",
        gap: 10,
        alignItems: "center",
      }}
    >
      <span style={{ fontSize: 13 }}>📄</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div
          style={{
            fontSize: 11,
            color: "#475569",
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {filename}
        </div>
        <div
          style={{
            fontSize: 10,
            color,
            fontWeight: 600,
            marginTop: 2,
          }}
        >
          {certNo && (
            <span
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                marginRight: 6,
              }}
            >
              {certNo}
            </span>
          )}
          {note}
        </div>
      </div>
    </div>
  );
}