"use client";

import React, { useEffect, useState, useCallback } from "react";
import Select from "react-select";
import AsyncSelect from "react-select/async";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { fetchApi } from "@/lib/api/http";
import {
  createCertificate,
  updateCertificate,
  getCertificate,
  CERTIFICATES_API_BASE_URL,
} from "@/lib/api/certificate.api";
import { useLegacyLookup } from "@/lib/api/hooks/useCertificates";
import type {
  CreateCertificateDto,
  CertType,
  VerificationDomain,
} from "@/lib/api/types/certificate.types";
import CertificateSuccessModal from "./CertificateSuccessModal";

// ✅ ADD 1 — import CompanyForm (same pattern as InquiryForm)
import CompanyForm from "./../../companies/Form/CompanyForm";

// ✅ NEW — real icons replacing emojis
import {
  Sparkles,
  RefreshCw,
  Repeat,
  Lightbulb,
  Pencil,
  AlertTriangle,
  Ban,
  Clipboard,
} from "lucide-react";

// ─── Type aliases (declared at top to avoid multi-line generics in useState) ───
type CompanyCache = {
  id: number;
  name: string;
  city: string;
  country?: string;
  scope_of_work?: string; // ✅ NEW — cached scope from companies API
};

type StandardItem = {
  id: number;
  name: string;
  title: string;
};

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

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

const DEFAULT_FORM = {
  company_id: undefined as number | undefined,
  standard_ids: [] as number[],
  cert_type: "" as CertType | "",
  city: "",
  country: "",
  scope_of_work: "",
  ea_codes: "",
  originally_registered: "",
  issue_date: "",
  expire_date: "",
  surveillance_audit_due: "",
  recertification_due: "",
  verification_domain: "local" as VerificationDomain,
};

// ✅ CHANGED — icon is now ReactNode (was string)
const CERT_TYPE_CARDS: {
  value: CertType;
  icon: React.ReactNode;
  title: string;
  desc: string;
  accent: string;
  bg: string;
}[] = [
  {
    value: "INITIAL",
    icon: <Sparkles size={20} strokeWidth={2} />,
    title: "Initial",
    desc: "First-time issuance — generates a new cert number",
    accent: "#2563eb",
    bg: "#eff6ff",
  },
  {
    value: "SURVEILLANCE",
    icon: <RefreshCw size={20} strokeWidth={2} />,
    title: "Surveillance",
    desc: "Annual renewal — reuses existing cert number",
    accent: "#d97706",
    bg: "#fffbeb",
  },
  {
    value: "RECERTIFICATION",
    icon: <Repeat size={20} strokeWidth={2} />,
    title: "Recertification",
    desc: "3-year full re-audit — reuses existing cert number",
    accent: "#7c3aed",
    bg: "#faf5ff",
  },
];

// ✅ NEW — helper to extract scope from any of the possible API response shapes
function extractScope(c: any): string {
  return (
    c?.scope_of_work ??
    c?.scopeOfWork ??
    c?.scope ??
    c?.scope_summary ??
    ""
  );
}

// ─── PreviewRow helper config — declared at MODULE LEVEL so JSX inside Record is unambiguous ───
type PreviewStyle = {
  bg: string;
  color: string;
  icon: React.ReactNode;
};

const PREVIEW_COLORS: Record<string, PreviewStyle> = {
  generate: {
    bg: "#dcfce7",
    color: "#15803d",
    icon: <Sparkles size={16} strokeWidth={2} />,
  },
  reuse: {
    bg: "#fef3c7",
    color: "#b45309",
    icon: <RefreshCw size={16} strokeWidth={2} />,
  },
  block: {
    bg: "#fee2e2",
    color: "#b91c1c",
    icon: <Ban size={16} strokeWidth={2} />,
  },
  manual: {
    bg: "#dbeafe",
    color: "#1d4ed8",
    icon: <Pencil size={16} strokeWidth={2} />,
  },
  "manual-empty": {
    bg: "#fef3c7",
    color: "#b45309",
    icon: <AlertTriangle size={16} strokeWidth={2} />,
  },
  unknown: {
    bg: "#f1f5f9",
    color: "#64748b",
    icon: <span>•</span>,
  },
  "pick-type": {
    bg: "#f1f5f9",
    color: "#64748b",
    icon: <span>•</span>,
  },
};

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

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

  // ✅ FIXED — use type alias instead of inline multi-line generic
  const [companies, setCompanies] = useState<CompanyCache[]>([]);
  const [standards, setStandards] = useState<StandardItem[]>([]);
  const [dropdownLoading, setDropdownLoading] = useState(false);

  const [selectedCompany, setSelectedCompany] = useState<SelectOption | null>(
    null,
  );

  // ✅ ADD 2 — state to open/close CompanyForm (same pattern as InquiryForm)
  const [showCompanyForm, setShowCompanyForm] = useState(false);

  // ✅ NEW 1 — manual cert numbers per standard (used for SURV/RECERT when no legacy match)
  const [manualCertNos, setManualCertNos] = useState<Record<number, string>>(
    {},
  );

  // ✅ NEW — track the original standard_ids loaded from the cert (so we can detect changes in edit mode)
  const [originalStandardIds, setOriginalStandardIds] = useState<number[]>([]);

  const {
    legacyRecords,
    legacyMap,
    lookup: lookupLegacy,
    reset: resetLegacy,
    loading: legacyLoading,
  } = useLegacyLookup();

  const [successData, setSuccessData] = useState<any>(null);

  useEffect(() => {
    if (!isOpen) return;
    setDropdownLoading(true);
    fetchApi<StandardItem[]>(`${CERTIFICATES_API_BASE_URL}/standards`)
      .then((standardRes) => {
        setStandards((standardRes ?? []) as StandardItem[]);
      })
      .catch(() => toast.error("Failed to load standards"))
      .finally(() => setDropdownLoading(false));
  }, [isOpen]);

  const loadCompanyOptions = async (
    inputValue: string,
  ): Promise<SelectOption[]> => {
    if (inputValue.trim().length < 2) return [];
    try {
      const res = await fetchApi<any>(
        `${CERTIFICATES_API_BASE_URL}/companies?limit=20&search=${encodeURIComponent(inputValue.trim())}`,
      );
      const companyList = res?.data ?? res ?? [];

      setCompanies((prev: CompanyCache[]) => {
        const existing = new Map<number, CompanyCache>(
          prev.map((c) => [c.id, c]),
        );
        companyList.forEach((c: any) => {
          existing.set(c.id, {
            id: c.id,
            name: c.name,
            city: c.city ?? "",
            country: c.country?.name ?? c.country ?? "",
            // ✅ NEW — capture scope_of_work from the API result
            scope_of_work: extractScope(c),
          });
        });
        return Array.from(existing.values());
      });

      return companyList.map((c: any) => ({
        value: c.id,
        label: `${c.name}${c.city ? ` — ${c.city}` : ""}`,
      }));
    } catch {
      return [];
    }
  };

  useEffect(() => {
    if (!isOpen || !editId) return;
    getCertificate(editId)
      .then(({ certificate: c }: any) => {
        const loadedStandardIds: number[] = c.standard?.id ? [c.standard.id] : [];

        setForm({
          company_id: c.company?.id,
          standard_ids: loadedStandardIds,
          cert_type: c.cert_type,
          city: c.city ?? "",
          country: c.country ?? "",
          scope_of_work: c.scope_of_work ?? "",
          ea_codes: c.ea_codes ?? "",
          originally_registered: c.originally_registered
            ? c.originally_registered.substring(0, 10)
            : "",
          issue_date: c.issue_date ? c.issue_date.substring(0, 10) : "",
          expire_date: c.expire_date ? c.expire_date.substring(0, 10) : "",
          surveillance_audit_due: c.surveillance_audit_due
            ? c.surveillance_audit_due.substring(0, 10)
            : "",
          recertification_due: c.recertification_due
            ? c.recertification_due.substring(0, 10)
            : "",
          verification_domain: c.verification_domain ?? "local",
        });

        // ✅ NEW — remember the original standards so we can warn user if they change them
        setOriginalStandardIds(loadedStandardIds);

        if (c.company) {
          setSelectedCompany({
            value: c.company.id,
            label: `${c.company.name}${c.company.city ? ` — ${c.company.city}` : ""}`,
          });
          setCompanies((prev: CompanyCache[]) => {
            if (prev.find((x) => x.id === c.company.id)) return prev;
            return [
              ...prev,
              {
                id: c.company.id,
                name: c.company.name,
                city: c.company.city ?? "",
                country: c.company.country?.name ?? c.company.country ?? "",
                scope_of_work: extractScope(c.company),
              },
            ];
          });
        }
      })
      .catch(() => toast.error("Failed to load certificate"));
  }, [isOpen, editId]);

  useEffect(() => {
    if (!isOpen) {
      setForm({ ...DEFAULT_FORM });
      setErrors({});
      resetLegacy();
      setSelectedCompany(null);
      setManualCertNos({});
      setOriginalStandardIds([]); // ✅ NEW — reset on close
    }
  }, [isOpen, resetLegacy]);

  const handleCompanyChange = useCallback(
    (opt: SelectOption | null) => {
      if (!opt) {
        setForm((f) => ({
          ...f,
          company_id: undefined,
          city: "",
          country: "",
          scope_of_work: "", // ✅ NEW — clear scope when company is cleared
        }));
        setSelectedCompany(null);
        resetLegacy();
        setManualCertNos({});
        return;
      }
      setSelectedCompany(opt);
      const company = companies.find((c) => c.id === opt.value);
      setForm((f) => ({
        ...f,
        company_id: Number(opt.value),
        city: company?.city ?? f.city,
        country: company?.country ?? f.country ?? "United Arab Emirates",
        // ✅ NEW — auto-fill scope from company (only if user hasn't typed something custom)
        scope_of_work:
          company?.scope_of_work && !f.scope_of_work.trim()
            ? company.scope_of_work
            : f.scope_of_work,
      }));
      const companyName = company?.name ?? String(opt.label).split(" — ")[0];
      if (companyName) lookupLegacy(companyName);
      setManualCertNos({});
    },
    [companies, lookupLegacy, resetLegacy],
  );

  // ✅ ADD 5 — handler for newly created company (called by CompanyForm onSuccess)
  const handleNewCompanyCreated = useCallback(
    (newCompany: {
      id: number;
      name: string;
      city?: string;
      country?: any;
      scope_of_work?: string;
      scopeOfWork?: string;
      scope?: string;
    }) => {
      const newScope = extractScope(newCompany);

      // Cache the new company
      setCompanies((prev: CompanyCache[]) => {
        if (prev.find((x) => x.id === newCompany.id)) return prev;
        return [
          ...prev,
          {
            id: newCompany.id,
            name: newCompany.name,
            city: newCompany.city ?? "",
            country: newCompany.country?.name ?? newCompany.country ?? "",
            scope_of_work: newScope,
          },
        ];
      });

      // Auto-select it in the form
      const opt: SelectOption = {
        value: newCompany.id,
        label: `${newCompany.name}${newCompany.city ? ` — ${newCompany.city}` : ""}`,
      };
      setSelectedCompany(opt);

      setForm((f) => ({
        ...f,
        company_id: newCompany.id,
        city: newCompany.city ?? f.city,
        country:
          newCompany.country?.name ??
          newCompany.country ??
          f.country ??
          "United Arab Emirates",
        // ✅ NEW — auto-fill scope from the newly created company
        scope_of_work: newScope && !f.scope_of_work.trim() ? newScope : f.scope_of_work,
      }));

      // Trigger legacy lookup for the new company
      if (newCompany.name) lookupLegacy(newCompany.name);

      setShowCompanyForm(false);
    },
    [lookupLegacy],
  );

  const getStandardShort = (standard: StandardItem) => {
    return standard.title
      ? standard.title
          .split(" ")
          .map((w: string) => w[0])
          .join("")
          .substring(0, 3)
          .toUpperCase()
      : standard.name.slice(0, 3).toUpperCase();
  };

  const perStandardPreview = form.standard_ids.map((sid) => {
    const std = standards.find((s) => s.id === sid);
    if (!std)
      return {
        standard_id: sid,
        standard_name: "?",
        short: "?",
        action: "unknown",
        cert_no: null as string | null,
        note: "",
      };
    const short = getStandardShort(std);
    const legacy = legacyMap[short];

    let action = "unknown";
    let cert_no: string | null = null;
    let note = "";

    if (!form.cert_type) {
      action = "pick-type";
      note = "Pick a certificate type first";
    } else if (form.cert_type === "INITIAL") {
      if (legacy) {
        action = "block";
        cert_no = legacy.cert_no;
        note = `Already exists as ${legacy.cert_no} — switch to Surveillance`;
      } else {
        action = "generate";
        note = "Will generate UAE-XX-XXX-YYYYY on submit";
      }
    } else {
      // SURVEILLANCE or RECERTIFICATION
      if (legacy) {
        action = "reuse";
        cert_no = legacy.cert_no;
        note = `Will reuse ${legacy.cert_no} from legacy`;
      } else {
        const manual = (manualCertNos[sid] ?? "").trim();
        if (manual) {
          action = "manual";
          cert_no = manual;
          note = `Will use manual cert no: ${manual}`;
        } else {
          action = "manual-empty";
          note =
            "No previous cert found in lookup — please enter the existing cert number manually below";
        }
      }
    }

    return {
      standard_id: sid,
      standard_name: std.name,
      short,
      action,
      cert_no,
      note,
    };
  });

  const hasAnyBlock =
    !isEdit &&
    perStandardPreview.some(
      (p) => p.action === "block" || p.action === "manual-empty",
    );

  const readyToSubmit = isEdit
    ? true
    : Boolean(form.company_id) &&
      form.standard_ids.length > 0 &&
      Boolean(form.cert_type) &&
      !hasAnyBlock;

  // ✅ NEW — detect if standards were changed in edit mode
  const standardsChangedInEdit =
    isEdit &&
    (form.standard_ids.length !== originalStandardIds.length ||
      form.standard_ids.some((id) => !originalStandardIds.includes(id)) ||
      originalStandardIds.some((id) => !form.standard_ids.includes(id)));

  // ✅ NEW — friendly names for "was → now" warning panel
  const oldStandardNames = originalStandardIds
    .map((id) => standards.find((s) => s.id === id)?.name)
    .filter(Boolean)
    .join(", ");
  const newStandardNames = form.standard_ids
    .map((id) => standards.find((s) => s.id === id)?.name)
    .filter(Boolean)
    .join(", ");

  const validate = (): boolean => {
    const e: Record<string, string> = {};
    if (!form.company_id) e.company_id = "Company is required";
    if (!form.standard_ids.length)
      e.standard_ids = "Pick at least one standard";
    if (!form.cert_type) e.cert_type = "Pick a certificate type";
    if (!form.city.trim()) e.city = "City is required";
    if (!form.country.trim()) e.country = "Country is required";
    if (!form.scope_of_work.trim())
      e.scope_of_work = "Scope of work is required";
    if (!form.ea_codes.trim()) e.ea_codes = "EA codes are required";
    if (!form.issue_date) e.issue_date = "Issue date is required";
    if (!form.expire_date) e.expire_date = "Expire date is required";
    if (!form.originally_registered)
      e.originally_registered = "Originally registered date is required";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async () => {
    if (!validate()) {
      toast.error("Please fix the errors in the form");
      return;
    }
    if (!isEdit && hasAnyBlock) {
      toast.error(
        "Some standards are blocked — please fix them before submitting",
      );
      return;
    }

    // ✅ NEW — Edit mode safety: this cert holds exactly ONE standard. Block if user somehow picked 0 or >1.
    if (isEdit && form.standard_ids.length !== 1) {
      toast.error(
        "This certificate holds exactly one standard. Please select exactly one in edit mode.",
      );
      return;
    }

    const dto: CreateCertificateDto = {
      company_id: form.company_id!,
      standard_ids: form.standard_ids,
      cert_type: form.cert_type as CertType,
      city: form.city,
      country: form.country,
      scope_of_work: form.scope_of_work,
      ea_codes: form.ea_codes,
      originally_registered: form.originally_registered,
      issue_date: form.issue_date,
      expire_date: form.expire_date,
      surveillance_audit_due: form.surveillance_audit_due || undefined,
      recertification_due: form.recertification_due || undefined,
      verification_domain: form.verification_domain,
    };

    setSaving(true);
    try {
      if (isEdit && editId) {
        // ✅ NEW — pass the (single) standard the user selected.
        // We send BOTH standard_ids[] (new shape, frontend canonical) AND standard_id (legacy, single)
        // so the backend works regardless of which it inspects.
        const singleStandardId = form.standard_ids[0];

        await updateCertificate(editId, {
          cert_type: form.cert_type as CertType,
          standard_id: singleStandardId,         // ✅ NEW — singular for backend update()
          standard_ids: [singleStandardId],      // ✅ NEW — also send array for consistency
          city: dto.city,
          country: dto.country,
          scope_of_work: dto.scope_of_work,
          ea_codes: dto.ea_codes,
          originally_registered: dto.originally_registered,
          issue_date: dto.issue_date,
          expire_date: dto.expire_date,
          surveillance_audit_due: dto.surveillance_audit_due,
          recertification_due: dto.recertification_due,
          verification_domain: dto.verification_domain,
        } as any);
        toast.success(
          standardsChangedInEdit
            ? "Certificate updated — standard swapped"
            : "Certificate updated",
        );
        refreshData?.();
        onClose();
      } else {
        const manualToSend: Record<number, string> = {};
        perStandardPreview.forEach((p) => {
          if (p.action === "manual" && p.cert_no) {
            manualToSend[p.standard_id] = p.cert_no;
          }
        });

        const payload: any = { ...dto };
        if (Object.keys(manualToSend).length > 0) {
          payload.manual_cert_numbers = manualToSend;
        }

        const result = await createCertificate(payload);
        toast.success(
          `${result.summary.total} certificate(s) created — ${result.summary.reused} reused, ${result.summary.generated} generated`,
        );
        setSuccessData(result);
        refreshData?.();
      }
    } catch (err: any) {
      toast.error(err.message ?? "Failed to save certificate");
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  return (
    <>
      {/* ✅ ADD 3 — CompanyForm modal on top */}
      <div
        style={{
          position: "fixed",
          inset: 0,
          zIndex: 9999,
          pointerEvents: showCompanyForm ? "auto" : "none",
        }}
      >
        <CompanyForm
          isOpen={showCompanyForm}
          onClose={() => setShowCompanyForm(false)}
          refreshData={() => {}}
          onSuccess={(newCompany: {
            id: number;
            name: string;
            city?: string;
            country?: any;
            scope_of_work?: string;
            scopeOfWork?: string;
            scope?: string;
          }) => {
            handleNewCompanyCreated(newCompany);
          }}
        />
      </div>

      <div className={styles.modalOverlay}>
        <div
          className={styles.modalContent}
          style={{ maxWidth: 1100, width: "95%" }}
        >
          <div className={styles.modalHeader}>
            <h2 className={styles.modalTitle}>
              {isEdit ? "Edit Certificate" : "Issue New Certificate"}
            </h2>
            <button
              className={styles.closeBtn}
              onClick={onClose}
              type="button"
            >
              ×
            </button>
          </div>

          <div className={styles.formBody}>
            <div className={styles.sectionHeader}>
              <span className={styles.sectionDot}></span>
              Company &amp; Certificate Type
            </div>

            <div className={styles.grid2}>
              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Company
                </label>
                <AsyncSelect
                  isDisabled={isEdit || dropdownLoading}
                  classNamePrefix="rselect"
                  loadOptions={loadCompanyOptions}
                  value={selectedCompany}
                  onChange={(opt) =>
                    handleCompanyChange(opt as SelectOption | null)
                  }
                  placeholder="Type company name to search... (min 2 chars)"
                  isSearchable
                  noOptionsMessage={({ inputValue }) =>
                    inputValue.length < 2
                      ? "Type at least 2 characters to search"
                      : "No companies found"
                  }
                  loadingMessage={() => "Searching companies..."}
                />
                {errors.company_id && (
                  <div className={styles.error}>{errors.company_id}</div>
                )}
                {!isEdit && !selectedCompany && (
                  <div
                    style={{
                      marginTop: 6,
                      fontSize: 11,
                      color: "#9ca3af",
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                    }}
                  >
                    <Lightbulb size={13} strokeWidth={2} />
                    Start typing to search from all companies
                  </div>
                )}

                {/* ✅ ADD 4 — "Add New Company" button */}
                {!isEdit && !selectedCompany && (
                  <button
                    type="button"
                    onClick={() => setShowCompanyForm(true)}
                    style={{
                      marginTop: 10,
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 6,
                      padding: "8px 16px",
                      borderRadius: 8,
                      cursor: "pointer",
                      fontSize: 12,
                      fontWeight: 700,
                      border: "1.5px dashed #14b8a6",
                      backgroundColor: "#f0fdfa",
                      color: "#0f766e",
                      transition: "all 0.15s",
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = "#ccfbf1";
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = "#f0fdfa";
                    }}
                  >
                    + Add New Company
                    <span
                      style={{
                        fontSize: 10,
                        fontWeight: 500,
                        color: "#0f766e",
                        opacity: 0.7,
                      }}
                    >
                      (not found in search?)
                    </span>
                  </button>
                )}
              </div>

              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Verification Domain
                </label>
                <select
                  className={styles.select}
                  value={form.verification_domain}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      verification_domain: e.target.value as VerificationDomain,
                    })
                  }
                >
                  <option value="local">Local (qrsyst.com)</option>
                  <option value="international">
                    International (qrs-intl.com)
                  </option>
                </select>
              </div>
            </div>

            <div className={styles.formGroup} style={{ marginTop: 16 }}>
              <label className={`${styles.label} ${styles.labelRequired}`}>
                Certificate Type
              </label>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(3,1fr)",
                  gap: 10,
                  marginTop: 6,
                }}
              >
                {CERT_TYPE_CARDS.map((card) => {
                  const sel = form.cert_type === card.value;
                  return (
                    <div
                      key={card.value}
                      onClick={() => {
                        setForm({ ...form, cert_type: card.value });
                      }}
                      style={{
                        border: `1.5px solid ${sel ? card.accent : "#e2e8f0"}`,
                        borderRadius: 9,
                        padding: "12px 14px",
                        cursor: "pointer",
                        transition: "all .15s",
                        background: sel ? card.bg : "#fff",
                        opacity: 1,
                        boxShadow: sel
                          ? `0 0 0 3px ${card.accent}22`
                          : undefined,
                      }}
                    >
                      <div
                        style={{
                          fontSize: 18,
                          marginBottom: 6,
                          color: card.accent,
                          display: "inline-flex",
                          alignItems: "center",
                        }}
                      >
                        {card.icon}
                      </div>
                      <div
                        style={{
                          fontSize: 12,
                          fontWeight: 800,
                          color: "#0f172a",
                          marginBottom: 3,
                        }}
                      >
                        {card.title}
                      </div>
                      <div
                        style={{
                          fontSize: 10,
                          color: "#64748b",
                          lineHeight: 1.4,
                        }}
                      >
                        {card.desc}
                      </div>
                    </div>
                  );
                })}
              </div>
              {errors.cert_type && (
                <div className={styles.error}>{errors.cert_type}</div>
              )}
              {isEdit && (
                <div
                  style={{
                    marginTop: 6,
                    fontSize: 11,
                    color: "#0f766e",
                    background: "#f0fdfa",
                    border: "1px dashed #14b8a6",
                    padding: "6px 10px",
                    borderRadius: 6,
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  <Pencil size={12} strokeWidth={2} />
                  You can switch the certificate type in edit mode.
                </div>
              )}
            </div>

            <div className={styles.sectionHeader}>
              <span className={styles.sectionDot}></span>
              Standards
            </div>

            <div className={styles.formGroup}>
              <label className={`${styles.label} ${styles.labelRequired}`}>
                ISO Standards
                <span
                  style={{
                    fontWeight: 400,
                    color: "#94a3b8",
                    marginLeft: 4,
                    fontSize: 11,
                  }}
                >
                  {isEdit
                    ? "(swap the existing standard — pick exactly one)"
                    : "(one cert will be created per standard)"}
                </span>
              </label>
              {/* ✅ FIX — only disable while loading; standards now editable in BOTH create AND edit modes.
                       In EDIT mode we render a SINGLE-select Select (each cert holds exactly one standard).
                       In CREATE mode we keep the multi-select to allow batch issuing. */}
              {isEdit ? (
                <Select
                  isDisabled={dropdownLoading}
                  classNamePrefix="rselect"
                  value={(() => {
                    const id = form.standard_ids[0];
                    if (!id) return null;
                    const std = standards.find((s) => s.id === id);
                    return std ? { value: std.id, label: std.name } : null;
                  })()}
                  options={standards.map((s) => ({
                    value: s.id,
                    label: s.name,
                  }))}
                  onChange={(opt) => {
                    const newId =
                      opt && (opt as any).value
                        ? Number((opt as any).value)
                        : null;
                    setForm({
                      ...form,
                      standard_ids: newId ? [newId] : [],
                    });
                  }}
                  placeholder="Select a standard..."
                  isClearable={false}
                />
              ) : (
                <Select
                  isDisabled={dropdownLoading}
                  isMulti
                  classNamePrefix="rselect"
                  value={standards
                    .filter((s) => form.standard_ids.includes(s.id))
                    .map((s) => ({ value: s.id, label: s.name }))}
                  options={standards.map((s) => ({
                    value: s.id,
                    label: s.name,
                  }))}
                  onChange={(opts) => {
                    const newIds = (opts ?? []).map((o: any) => Number(o.value));
                    setForm({
                      ...form,
                      standard_ids: newIds,
                    });
                    setManualCertNos((prev) => {
                      const next: Record<number, string> = {};
                      newIds.forEach((id) => {
                        if (prev[id] !== undefined) next[id] = prev[id];
                      });
                      return next;
                    });
                  }}
                  placeholder="Select standards..."
                />
              )}
              {errors.standard_ids && (
                <div className={styles.error}>{errors.standard_ids}</div>
              )}

              {/* ✅ NEW — Edit-mode hint about standards being editable */}
              {isEdit && (
                <div
                  style={{
                    marginTop: 6,
                    fontSize: 11,
                    color: "#0f766e",
                    background: "#f0fdfa",
                    border: "1px dashed #14b8a6",
                    padding: "6px 10px",
                    borderRadius: 6,
                    display: "flex",
                    alignItems: "flex-start",
                    gap: 6,
                  }}
                >
                  <Pencil
                    size={12}
                    strokeWidth={2}
                    style={{ marginTop: 2, flexShrink: 0 }}
                  />
                  <span>
                    You can swap this certificate's standard. Each certificate
                    holds exactly ONE standard — to add another standard for the
                    same company, issue a new certificate from the create flow.
                  </span>
                </div>
              )}

              {/* ✅ NEW — Warn user prominently if they actually changed standards */}
              {isEdit && standardsChangedInEdit && (
                <div
                  style={{
                    marginTop: 6,
                    fontSize: 11.5,
                    color: "#92400e",
                    background: "#fffbeb",
                    border: "1px solid #fcd34d",
                    padding: "8px 12px",
                    borderRadius: 6,
                    fontWeight: 600,
                  }}
                >
                  <div
                    style={{ display: "flex", alignItems: "center", gap: 6 }}
                  >
                    <AlertTriangle size={14} strokeWidth={2.2} />
                    Standard will be swapped
                  </div>
                  <div
                    style={{
                      fontWeight: 400,
                      color: "#a16207",
                      marginTop: 4,
                      fontSize: 11,
                      lineHeight: 1.5,
                    }}
                  >
                    From: <strong>{oldStandardNames || "—"}</strong>
                    <br />
                    To: <strong>{newStandardNames || "—"}</strong>
                    <br />
                    The certificate's standard reference will be replaced. Cert
                    number, dates, scope, and history are preserved.
                  </div>
                </div>
              )}
            </div>

            {!isEdit &&
              form.company_id &&
              form.standard_ids.length > 0 &&
              form.cert_type && (
                <div style={{ marginTop: 12 }}>
                  <div
                    style={{
                      fontSize: 11,
                      fontWeight: 800,
                      color: "#94a3b8",
                      letterSpacing: ".08em",
                      textTransform: "uppercase",
                      marginBottom: 8,
                    }}
                  >
                    Preview — what will happen on submit
                  </div>
                  {legacyLoading && (
                    <div style={{ fontSize: 12, color: "#64748b", padding: 8 }}>
                      Checking legacy records...
                    </div>
                  )}
                  <div
                    style={{ display: "flex", flexDirection: "column", gap: 6 }}
                  >
                    {perStandardPreview.map((p) => (
                      <PreviewRow
                        key={p.standard_id}
                        preview={p}
                        manualValue={manualCertNos[p.standard_id] ?? ""}
                        onManualChange={(val) =>
                          setManualCertNos((prev) => ({
                            ...prev,
                            [p.standard_id]: val,
                          }))
                        }
                      />
                    ))}
                  </div>
                  {legacyRecords.length > 0 && (
                    <div
                      style={{
                        marginTop: 10,
                        padding: "8px 12px",
                        fontSize: 11,
                        color: "#475569",
                        background: "#f8fafc",
                        border: "1px solid #e2e8f0",
                        borderRadius: 6,
                        display: "flex",
                        alignItems: "center",
                        gap: 6,
                      }}
                    >
                      <Clipboard size={13} strokeWidth={2} />
                      Found {legacyRecords.length} legacy record(s) in /api/excel
                      for this company
                    </div>
                  )}
                </div>
              )}

            <div className={styles.sectionHeader}>
              <span className={styles.sectionDot}></span>
              Certificate Details
            </div>

            <div className={styles.grid2}>
              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  City
                </label>
                <input
                  className={`${styles.input} ${errors.city ? styles.inputError : ""}`}
                  value={form.city}
                  onChange={(e) => setForm({ ...form, city: e.target.value })}
                />
                {errors.city && (
                  <div className={styles.error}>{errors.city}</div>
                )}
              </div>
              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Country
                </label>
                <input
                  className={`${styles.input} ${errors.country ? styles.inputError : ""}`}
                  value={form.country}
                  onChange={(e) =>
                    setForm({ ...form, country: e.target.value })
                  }
                />
                {errors.country && (
                  <div className={styles.error}>{errors.country}</div>
                )}
              </div>
            </div>

            {/* ✅ NEW — Scope of Work auto-filled from company, larger textarea */}
            <div className={styles.formGroup} style={{ marginTop: 12 }}>
              <label className={`${styles.label} ${styles.labelRequired}`}>
                Scope of Work
                <span
                  style={{
                    fontWeight: 400,
                    color: "#94a3b8",
                    marginLeft: 6,
                    fontSize: 11,
                  }}
                >
                  (auto-filled from company — editable)
                </span>
              </label>
              <textarea
                className={`${styles.textarea} ${errors.scope_of_work ? styles.inputError : ""}`}
                rows={8}
                style={{
                  minHeight: 180,
                  resize: "vertical",
                  lineHeight: 1.5,
                  fontFamily: "inherit",
                  width: "100%",
                }}
                value={form.scope_of_work}
                onChange={(e) =>
                  setForm({ ...form, scope_of_work: e.target.value })
                }
                placeholder="Detailed description of activities, products, or services to be certified..."
              />
              {errors.scope_of_work && (
                <div className={styles.error}>{errors.scope_of_work}</div>
              )}
            </div>

            <div className={styles.formGroup} style={{ marginTop: 12 }}>
              <label className={`${styles.label} ${styles.labelRequired}`}>
                EA Codes
              </label>
              <input
                className={`${styles.input} ${errors.ea_codes ? styles.inputError : ""}`}
                placeholder="e.g. 17"
                value={form.ea_codes}
                onChange={(e) =>
                  setForm({ ...form, ea_codes: e.target.value })
                }
              />
              {errors.ea_codes && (
                <div className={styles.error}>{errors.ea_codes}</div>
              )}
            </div>

            <div className={styles.sectionHeader}>
              <span className={styles.sectionDot}></span>
              Dates
            </div>

            <div className={styles.grid3}>
              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Originally Registered
                </label>
                <input
                  type="date"
                  className={`${styles.input} ${errors.originally_registered ? styles.inputError : ""}`}
                  value={form.originally_registered}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      originally_registered: e.target.value,
                    })
                  }
                />
                {errors.originally_registered && (
                  <div className={styles.error}>
                    {errors.originally_registered}
                  </div>
                )}
              </div>
              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Issue Date
                </label>
                <input
                  type="date"
                  className={`${styles.input} ${errors.issue_date ? styles.inputError : ""}`}
                  value={form.issue_date}
                  onChange={(e) =>
                    setForm({ ...form, issue_date: e.target.value })
                  }
                />
                {errors.issue_date && (
                  <div className={styles.error}>{errors.issue_date}</div>
                )}
              </div>
              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Expire Date
                </label>
                <input
                  type="date"
                  className={`${styles.input} ${errors.expire_date ? styles.inputError : ""}`}
                  value={form.expire_date}
                  onChange={(e) =>
                    setForm({ ...form, expire_date: e.target.value })
                  }
                />
                {errors.expire_date && (
                  <div className={styles.error}>{errors.expire_date}</div>
                )}
              </div>
            </div>

            <div className={styles.grid2} style={{ marginTop: 12 }}>
              <div className={styles.formGroup}>
                <label className={styles.label}>Surv. Audit On or Before</label>
                <input
                  type="date"
                  className={styles.input}
                  value={form.surveillance_audit_due}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      surveillance_audit_due: e.target.value,
                    })
                  }
                />
                <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                  Prints as <strong>SURV. AUDIT ON OR BEFORE</strong> on the
                  certificate
                </div>
              </div>
              <div className={styles.formGroup}>
                <label className={styles.label}>Re-certification Due On</label>
                <input
                  type="date"
                  className={styles.input}
                  value={form.recertification_due}
                  onChange={(e) =>
                    setForm({ ...form, recertification_due: e.target.value })
                  }
                />
                <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                  Prints as <strong>RE-CERTIFICATION DUE ON</strong> on the
                  certificate
                </div>
              </div>
            </div>
          </div>

          <div className={styles.modalFooter}>
            <button
              className={styles.btnCancel}
              type="button"
              onClick={onClose}
            >
              Cancel
            </button>
            <button
              className={styles.btnSubmit}
              type="button"
              onClick={handleSubmit}
              disabled={saving || (!isEdit && !readyToSubmit)}
              title={
                !readyToSubmit && !isEdit
                  ? "Please complete the form — some fields may be missing or blocked"
                  : ""
              }
              style={{
                opacity: saving || (!isEdit && !readyToSubmit) ? 0.5 : 1,
              }}
            >
              {saving
                ? "Saving..."
                : isEdit
                  ? "Update Certificate"
                  : `Issue ${form.standard_ids.length || ""} Certificate${
                      form.standard_ids.length === 1 ? "" : "s"
                    }`}
            </button>
          </div>
        </div>
      </div>

      {successData && (
        <CertificateSuccessModal
          data={successData}
          onClose={() => {
            setSuccessData(null);
            onClose();
          }}
        />
      )}
    </>
  );
}

function PreviewRow({
  preview,
  manualValue,
  onManualChange,
}: {
  preview: {
    standard_id: number;
    standard_name: string;
    short: string;
    action: string;
    cert_no: string | null;
    note: string;
  };
  manualValue?: string;
  onManualChange?: (val: string) => void;
}) {
  // ✅ Uses module-level PREVIEW_COLORS to avoid TS confusion with JSX inside Record<>
  const style = PREVIEW_COLORS[preview.action] ?? PREVIEW_COLORS.unknown;

  const isManualMode =
    preview.action === "manual" || preview.action === "manual-empty";

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 8,
        padding: "8px 12px",
        background: style.bg,
        border: `1px solid ${style.color}33`,
        borderRadius: 6,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <span
          style={{
            fontSize: 16,
            color: style.color,
            display: "inline-flex",
            alignItems: "center",
          }}
        >
          {style.icon}
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "#0f172a" }}>
            {preview.standard_name}{" "}
            <span
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                fontSize: 10,
                color: "#94a3b8",
                fontWeight: 400,
              }}
            >
              ({preview.short})
            </span>
          </div>
          <div style={{ fontSize: 11, color: style.color, marginTop: 2 }}>
            {preview.note}
          </div>
        </div>
        {preview.cert_no && !isManualMode && (
          <span
            style={{
              fontFamily: "'IBM Plex Mono', monospace",
              fontSize: 12,
              fontWeight: 700,
              color: style.color,
              padding: "3px 8px",
              background: "#fff",
              borderRadius: 4,
              border: `1px solid ${style.color}55`,
            }}
          >
            {preview.cert_no}
          </span>
        )}
      </div>

      {isManualMode && (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            paddingLeft: 28,
          }}
        >
          <label
            style={{
              fontSize: 10,
              fontWeight: 700,
              color: "#475569",
              letterSpacing: ".05em",
              textTransform: "uppercase",
              whiteSpace: "nowrap",
            }}
          >
            Cert No:
          </label>
          <input
            type="text"
            value={manualValue ?? ""}
            onChange={(e) => onManualChange?.(e.target.value)}
            placeholder="e.g. UAE-22-001-12345"
            style={{
              flex: 1,
              padding: "6px 10px",
              fontSize: 12,
              fontFamily: "'IBM Plex Mono', monospace",
              fontWeight: 600,
              border: `1.5px solid ${preview.action === "manual-empty" ? "#fbbf24" : "#3b82f6"}`,
              borderRadius: 5,
              background: "#fff",
              outline: "none",
              color: "#0f172a",
            }}
          />
        </div>
      )}
    </div>
  );
}