"use client";

import React, { useEffect, useState } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { fetchApi } from "@/lib/api/http";
import {
  addManualLegacy,
  updateLegacy,
  getLegacyById,
  type CreateLegacyDto,
} from "@/lib/api/legacy.api";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

interface SelectOption {
  value: string;
  label: string;
}

interface Props {
  isOpen: boolean;
  onClose: () => void;
  refreshData?: (toastMessage?: string) => void;
  editId?: number | null;
}

const DEFAULT_FORM = {
  company_name: "",
  standards: [] as string[],
  orginally_reg: "",
  issue_date: "",
  expire_date: "",
  status: "QRS",
};

const STANDARD_OPTIONS: SelectOption[] = [
  { value: "ISO 9001:2015", label: "ISO 9001:2015 — Quality (QMS)" },
  { value: "ISO 14001:2015", label: "ISO 14001:2015 — Environmental (EMS)" },
  { value: "ISO 45001:2018", label: "ISO 45001:2018 — Health & Safety (OHA)" },
  { value: "ISO 22000:2018", label: "ISO 22000:2018 — Food Safety (FSMS)" },
  { value: "ISO 27001:2022", label: "ISO 27001:2022 — Info Security (ISMS)" },
  { value: "ISO 13485:2016", label: "ISO 13485:2016 — Medical Devices" },
  { value: "ISO 50001:2018", label: "ISO 50001:2018 — Energy Management" },
  { value: "HACCP", label: "HACCP — Hazard Analysis Critical Control Point" },
  { value: "HALAL", label: "HALAL MANAGEMENT SYSTEM" },
  { value: "IMS", label: "IMS — Integrated (9001+14001+45001)" },
  { value: "QMS", label: "QMS (ISO 9001 short)" },
  { value: "EMS", label: "EMS (ISO 14001 short)" },
  { value: "OHA", label: "OHA (ISO 45001 short)" },
  { value: "FSMS", label: "FSMS (ISO 22000 short)" },
  { value: "GMP", label: "GMP" },
  { value: "20000-1:2018", label: "Service management system (SMS) standard" },
  { value: "10002:2018", label: "Quality management Customer satisfaction" },
];

function getShortCode(standardLabel: string): string {
  const upper = standardLabel.toUpperCase();
  if (upper === "IMS") return "IMS";
  if (upper.includes("9001")) return "QMS";
  if (upper.includes("14001")) return "EMS";
  if (upper.includes("45001")) return "OHA";
  if (upper.includes("22000") || upper === "FSMS") return "FSMS";
  if (upper.includes("27001") || upper === "ISMS") return "ISMS";
  if (upper.includes("13485")) return "MDQ";
  if (upper.includes("50001")) return "ENS";
  if (upper === "HACCP") return "HACCP";
  if (upper === "HALAL") return "HAL";
  if (upper === "QMS") return "QMS";
  if (upper === "EMS") return "EMS";
  if (upper === "OHA") return "OHA";
  if (upper === "GMP") return "GMP";
  if (upper === "20000-1:2018") return "SMS";
  if (upper === "10002:2018") return "QMCS";

  return upper.slice(0, 4);
}

function expandSelectedStandards(
  selected: string[],
): { code: string; label: string }[] {
  const result: { code: string; label: string }[] = [];
  const seen = new Set<string>();

  for (const std of selected) {
    const upper = std.toUpperCase();
    if (upper === "IMS") {
      [
        { code: "QMS", label: "ISO 9001:2015 (QMS)" },
        { code: "EMS", label: "ISO 14001:2015 (EMS)" },
        { code: "OHA", label: "ISO 45001:2018 (OHA)" },
      ].forEach((s) => {
        if (!seen.has(s.code)) {
          seen.add(s.code);
          result.push(s);
        }
      });
    } else {
      const code = getShortCode(std);
      if (!seen.has(code)) {
        seen.add(code);
        result.push({ code, label: std });
      }
    }
  }
  return result;
}

// ✅ NEW HELPER — Map short codes back to full ISO names for edit hydration
function shortCodeToFullName(code: string): string {
  const upper = code.toUpperCase();
  if (upper === "QMS") return "ISO 9001:2015";
  if (upper === "EMS") return "ISO 14001:2015";
  if (upper === "OHA") return "ISO 45001:2018";
  if (upper === "FSMS") return "ISO 22000:2018";
  if (upper === "ISMS") return "ISO 27001:2022";
  if (upper === "MDQ") return "ISO 13485:2016";
  if (upper === "ENS") return "ISO 50001:2018";
  if (upper === "ENS") return "ISO 50001:2018";
  if (upper === "HACCP") return "HACCP";
  if (upper === "HAL" || upper === "HALAL") return "HALAL";
  if (upper === "IMS") return "IMS";
  return code;
}

export default function LegacyForm({
  isOpen,
  onClose,
  refreshData,
  editId,
}: Props) {
  const isEdit = Boolean(editId);

  const [form, setForm] = useState({ ...DEFAULT_FORM });
  const [perStandardCerts, setPerStandardCerts] = useState<
    Record<string, string>
  >({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);
  const [loadingEdit, setLoadingEdit] = useState(false);

  // ── Hydrate on edit ─────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getLegacyById(editId)
        .then((cert) => {
          // ✅ FIX — Parse standards from short codes (QMS,EMS) → full names (ISO 9001:2015,...)
          // This handles both old data (full ISO names) AND new data (short codes)
          const rawStandards = (cert.standard || "")
            .split(",")
            .map((s) => s.trim())
            .filter(Boolean);

          const standardsArray = rawStandards.map((s) => {
            // If already in full ISO format, keep as-is
            if (s.toUpperCase().startsWith("ISO")) return s;
            // If it's a short code, convert back to full name for the dropdown
            return shortCodeToFullName(s);
          });

          setForm({
            company_name: cert.company_name || "",
            standards: standardsArray,
            orginally_reg: cert.orginally_reg
              ? cert.orginally_reg.substring(0, 10)
              : "",
            issue_date: cert.issue_date ? cert.issue_date.substring(0, 10) : "",
            expire_date: cert.expire_date
              ? cert.expire_date.substring(0, 10)
              : "",
            status: cert.status || "QRS",
          });

          const expanded = expandSelectedStandards(standardsArray);
          const certParts = (cert.cert_no || "")
            .split(",")
            .map((s) => s.trim())
            .filter(Boolean);

          let pfx = "";
          const resolved = certParts.map((p) => {
            if (p.includes("-")) {
              pfx = p.split("-")[0];
              return p;
            }
            return pfx + "-" + p;
          });

          const certs: Record<string, string> = {};
          expanded.forEach((s, idx) => {
            certs[s.code] = resolved[idx] || "";
          });
          setPerStandardCerts(certs);
        })
        .catch(() => toast.error("Failed to load previous certificate"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT_FORM });
      setPerStandardCerts({});
      setErrors({});
    }
  }, [isOpen, editId]);

  // ── When standards change, sync per-standard cert numbers ───────────────
  useEffect(() => {
    if (form.standards.length === 0) {
      setPerStandardCerts({});
      return;
    }
    const expanded = expandSelectedStandards(form.standards);
    setPerStandardCerts((prev) => {
      const next: Record<string, string> = {};
      expanded.forEach((s) => {
        next[s.code] = prev[s.code] || "";
      });
      return next;
    });
  }, [form.standards]);

  // ── Validation ──────────────────────────────────────────────────────────
  const validate = (): boolean => {
    const e: Record<string, string> = {};

    if (!form.company_name.trim()) e.company_name = "Company name is required";
    if (form.standards.length === 0) e.standards = "Pick at least one standard";

    const expanded = expandSelectedStandards(form.standards);
    for (const s of expanded) {
      const certNo = perStandardCerts[s.code]?.trim();
      if (!certNo) {
        e[`cert_${s.code}`] = `Certificate number for ${s.code} is required`;
      } else if (certNo.length < 3) {
        e[`cert_${s.code}`] = `Min 3 characters`;
      }
    }

    setErrors(e);
    return Object.keys(e).length === 0;
  };

  // ── Submit ──────────────────────────────────────────────────────────────
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) {
      toast.error("Please fix the errors in the form");
      return;
    }

    setSaving(true);

    try {
      const expanded = expandSelectedStandards(form.standards);
      const certNos = expanded.map((s) => perStandardCerts[s.code].trim());
      const combinedCertNo = certNos.join(",");

      // ✅ THE FIX — Save as SHORT CODES (QMS, EMS, OHA) instead of full ISO names
      // This way the Certificate Form's lookup will find them via getStandardShort()
      const combinedStandards = expanded.map((s) => s.code).join(",");

      const dto: CreateLegacyDto = {
        cert_no: combinedCertNo,
        company_name: form.company_name.trim(),
        standard: combinedStandards,
        orginally_reg: form.orginally_reg || undefined,
        issue_date: form.issue_date || undefined,
        expire_date: form.expire_date || undefined,
        status: form.status || "QRS",
      };

      if (isEdit && editId) {
        const result = await updateLegacy(editId, dto);
        const message = `✅ Previous certificate updated! Cert: ${result.cert_no}`;
        onClose();
        refreshData?.(message);
      } else {
        const result = await addManualLegacy(dto);
        const message = `✅ Previous certificate added! Cert: ${result.cert_no} (${expanded.length} standard${expanded.length > 1 ? "s" : ""})`;
        onClose();
        refreshData?.(message);
      }
    } catch (err: any) {
      toast.error(err.message ?? "Failed to save previous certificate", {
        duration: 5000,
      });
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  const expandedStandards = expandSelectedStandards(form.standards);

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 720, width: "95%" }}
      >
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>
              {isEdit
                ? "✏️ Edit Previous Certificate"
                : "📋 Add Previous Certificate"}
            </h2>
            <p className={styles.modalSubtitle}>
              {isEdit
                ? "Update previous certificate details"
                : "Add a previous certificate (overseas client or migration)"}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">
            ✕
          </button>
        </div>

        {loadingEdit ? (
          <div className={styles.loadingSpinner}>
            <div className={styles.loadingSpinnerIcon} />
            Loading previous certificate data...
          </div>
        ) : (
          <form onSubmit={handleSubmit} className={styles.form}>
            <div className={styles.formBody}>
              {/* ══ Company Section ══ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />
                Company Details
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label}>
                  Company Name <span style={{ color: "#ef4444" }}>*</span>
                </label>
                <input
                  type="text"
                  value={form.company_name}
                  placeholder="e.g. OVERSEAS TRADING LLC"
                  onChange={(e) =>
                    setForm((p) => ({ ...p, company_name: e.target.value }))
                  }
                  className={`${styles.input} ${errors.company_name ? styles.inputError : ""}`}
                />
                {errors.company_name && (
                  <span className={styles.error}>{errors.company_name}</span>
                )}
              </div>

              {/* ══ Standards Section (multi-select) ══ */}
              <div className={styles.sectionHeader} style={{ marginTop: 20 }}>
                <span className={styles.sectionDot} />
                Standards <span style={{ color: "#ef4444" }}>*</span>
                <span
                  style={{
                    fontWeight: 400,
                    color: "#94a3b8",
                    marginLeft: 6,
                    fontSize: 11,
                    textTransform: "none",
                  }}
                >
                  (you can select multiple)
                </span>
              </div>

              <div className={styles.formGroup}>
                <Select
                  classNamePrefix="rselect"
                  isMulti
                  options={STANDARD_OPTIONS}
                  value={STANDARD_OPTIONS.filter((o) =>
                    form.standards.includes(o.value),
                  )}
                  onChange={(opts) =>
                    setForm((p) => ({
                      ...p,
                      standards: (opts ?? []).map((o: any) => o.value),
                    }))
                  }
                  placeholder="Select one or more standards..."
                  isSearchable
                  closeMenuOnSelect={false}
                  styles={{
                    control: (b: any) => ({
                      ...b,
                      borderColor: errors.standards ? "#ef4444" : "#e5e7eb",
                      minHeight: 42,
                    }),
                  }}
                />
                {errors.standards && (
                  <span className={styles.error}>{errors.standards}</span>
                )}
                <div style={{ marginTop: 6, fontSize: 11, color: "#9ca3af" }}>
                  💡 Selecting <strong>IMS</strong> auto-includes QMS + EMS +
                  OHA. Each selected standard needs its own cert number.
                </div>
              </div>

              {/* ══ Per-Standard Cert Numbers ══ */}
              {expandedStandards.length > 0 && (
                <>
                  <div
                    className={styles.sectionHeader}
                    style={{ marginTop: 20 }}
                  >
                    <span className={styles.sectionDot} />
                    Certificate Number{expandedStandards.length > 1
                      ? "s"
                      : ""}{" "}
                    <span style={{ color: "#ef4444" }}>*</span>
                    <span
                      style={{
                        fontWeight: 400,
                        color: "#94a3b8",
                        marginLeft: 6,
                        fontSize: 11,
                        textTransform: "none",
                      }}
                    >
                      ({expandedStandards.length} cert
                      {expandedStandards.length > 1 ? "s" : ""} required)
                    </span>
                  </div>

                  <div
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      gap: 12,
                      padding: 12,
                      background:
                        "linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%)",
                      border: "1px solid #99f6e4",
                      borderRadius: 10,
                    }}
                  >
                    {expandedStandards.map((s) => (
                      <div
                        key={s.code}
                        style={{
                          display: "grid",
                          gridTemplateColumns: "auto 1fr",
                          gap: 12,
                          alignItems: "start",
                        }}
                      >
                        <div
                          style={{
                            display: "flex",
                            flexDirection: "column",
                            alignItems: "center",
                            justifyContent: "center",
                            padding: "10px 14px",
                            backgroundColor: "#fff",
                            border: "1.5px solid #14b8a6",
                            borderRadius: 8,
                            minWidth: 120,
                          }}
                        >
                          <div
                            style={{
                              fontSize: 14,
                              fontWeight: 800,
                              color: "#0f766e",
                              fontFamily: "'IBM Plex Mono', monospace",
                            }}
                          >
                            {s.code}
                          </div>
                          <div
                            style={{
                              fontSize: 10,
                              color: "#64748b",
                              marginTop: 2,
                              textAlign: "center",
                            }}
                          >
                            {s.label}
                          </div>
                        </div>
                        <div>
                          <input
                            type="text"
                            value={perStandardCerts[s.code] ?? ""}
                            placeholder={`e.g. ${s.code === "QMS"
                              ? "AAU-30638"
                              : s.code === "EMS"
                                ? "ADU-2687"
                                : s.code === "OHA"
                                  ? "AAH-12345"
                                  : "QRS-INT-2026-001"
                              }`}
                            onChange={(e) =>
                              setPerStandardCerts((p) => ({
                                ...p,
                                [s.code]: e.target.value,
                              }))
                            }
                            className={`${styles.input} ${errors[`cert_${s.code}`] ? styles.inputError : ""}`}
                            style={{
                              fontFamily: "'IBM Plex Mono', monospace",
                              fontSize: 13,
                              letterSpacing: 0.3,
                              height: 42,
                            }}
                          />
                          {errors[`cert_${s.code}`] && (
                            <span className={styles.error}>
                              {errors[`cert_${s.code}`]}
                            </span>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </>
              )}

              {/* ══ Dates Section ══ */}
              <div className={styles.sectionHeader} style={{ marginTop: 20 }}>
                <span className={styles.sectionDot} />
                Dates (optional but recommended)
              </div>

              <div className={styles.grid3}>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Originally Registered</label>
                  <input
                    type="date"
                    value={form.orginally_reg}
                    onChange={(e) =>
                      setForm((p) => ({ ...p, orginally_reg: e.target.value }))
                    }
                    className={styles.input}
                  />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Issue Date</label>
                  <input
                    type="date"
                    value={form.issue_date}
                    onChange={(e) =>
                      setForm((p) => ({ ...p, issue_date: e.target.value }))
                    }
                    className={styles.input}
                  />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Expire Date</label>
                  <input
                    type="date"
                    value={form.expire_date}
                    onChange={(e) =>
                      setForm((p) => ({ ...p, expire_date: e.target.value }))
                    }
                    className={styles.input}
                  />
                </div>
              </div>

              {/* ══ Status / Source ══ */}
              <div className={styles.sectionHeader} style={{ marginTop: 20 }}>
                <span className={styles.sectionDot} />
                Source / Status
              </div>

              <div className={styles.formGroup}>
                <select
                  value={form.status}
                  onChange={(e) =>
                    setForm((p) => ({ ...p, status: e.target.value }))
                  }
                  className={styles.select}
                >
                  <option value="QRS">QRS (UAE local)</option>
                  <option value="TQS">TQS (overseas/international)</option>
                  <option value="MIGRATION">MIGRATION (from old system)</option>
                  <option value="OTHER">OTHER</option>
                </select>
              </div>

              {/* ══ Info notice ══ */}
              <div
                style={{
                  marginTop: 20,
                  padding: "10px 14px",
                  backgroundColor: "#fef9c3",
                  border: "1px solid #fde047",
                  borderRadius: 8,
                  fontSize: 12,
                  color: "#854d0e",
                }}
              >
                💡 <strong>Tip:</strong> Once added, this previous certificate
                will be auto-detected when you issue
                surveillance/recertification certificates for this company.
              </div>
            </div>

            {/* ── Footer ────────────────────────────────────────── */}
            <div className={styles.modalFooter}>
              <button
                type="button"
                onClick={onClose}
                className={styles.cancelBtn}
                disabled={saving}
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={saving}
                className={styles.saveBtn}
                style={{
                  opacity: saving ? 0.6 : 1,
                  cursor: saving ? "not-allowed" : "pointer",
                }}
              >
                {saving
                  ? isEdit
                    ? "⏳ Updating..."
                    : "⏳ Saving..."
                  : isEdit
                    ? "✏️ Update Previous Cert"
                    : "+ Add Previous Cert"}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
