"use client";

import React, { useEffect, useState, useCallback } from "react";
import { Building2, Landmark, Check } from "lucide-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 { getClientsPagedAll, getClientDetails } from "@/lib/api/clients.api";
import { mapClientsToSearchRows } from "@/lib/api/mappers/clients.mappers";
import type { ClientSearchRow } from "@/lib/api/types/clients.types";

import {
  createAuditRequest,
  updateAuditRequest,
  getAuditRequest,
  AUDIT_REQUESTS_API_BASE_URL,
} from "@/lib/api/audit-request.api";
import type {
  CreateAuditRequestDto,
  AuditMode,
  CertificationType,
  AuditRequestStatus,
} from "@/lib/api/types/audit-request.types";

// ─── Type aliases ──────────────────────────────────────────────────────────
type CompanyOpt = {
  id: number;
  name: string;
  city?: string;
  email?: string;
  contact_person?: string;
  mobile?: string;
};
type StandardOpt = { id: number; name: string; title?: string };

// Shape of a stored document (matches the backend `documents` JSON column)
type StoredDoc = {
  doc_type?: string;   // 🆕 'trade_license' | 'previous_certificate' | 'other'
  filename: string;
  path: string;
  mimetype: string;
  size: number;
};

interface SelectOption {
  value: number | string;
  label: string;
  raw?: ClientSearchRow;
}

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

// NOTE: kept for reference — the "Proposed Time" field now uses a native
// time picker (<input type="time">) instead of this fixed dropdown.
const TIME_OPTIONS: { label: string; time: string }[] = [
  { label: "09.00AM", time: "09:00:00" },
  { label: "10.00AM", time: "10:00:00" },
  { label: "11.00AM", time: "11:00:00" },
  { label: "12.00PM", time: "12:00:00" },
  { label: "01.00PM", time: "13:00:00" },
  { label: "02.00PM", time: "14:00:00" },
  { label: "03.00PM", time: "15:00:00" },
  { label: "04.00PM", time: "16:00:00" },
];

const CERTIFICATION_TYPE_OPTIONS: {
  value: CertificationType;
  label: string;
}[] = [
    { value: "INITIAL", label: "Initial Certification" },
    { value: "SURVEILLANCE", label: "Surveillance" },        // 🆕 add this
    { value: "SURVEILLANCE_1", label: "1st Surveillance" },
    { value: "SURVEILLANCE_2", label: "2nd Surveillance" },
    { value: "RECERTIFICATION", label: "Re-Certification" },
    { value: "SURVEILLANCE_RECERT", label: "Surveillance & Re-Certification" },
    { value: "Recertification or renewal", label: "Recertification or Renewal" },
  ];

const AUDIT_MODE_OPTIONS: { value: AuditMode; label: string }[] = [
  { value: "ONLINE", label: "💻 Online" },
  { value: "ONSITE", label: "🏢 On-site" },
  { value: "HYBRID", label: "🔀 Hybrid" },
];

const ACCREDITATION_OPTIONS: SelectOption[] = [
  { value: "ASCB", label: "ASCB" },
  { value: "IAS", label: "IAS" },
  { value: "EIAC", label: "EIAC" },
  { value: "UAF", label: "UAF" },
  { value: "IAF", label: "IAF" },
  { value: "OTHER", label: "Other" },

];

const DEFAULTS = {
  company_id: 0 as number,
  client_group: "QRS" as "QRS" | "TQS",   // 🆕
  auditee_name: "",
  auditee_contact: "",
  auditee_email: "",
  standard_ids: [] as number[],
  certification_type: "SURVEILLANCE_1" as CertificationType,
  accreditation: "ASCB",
  proposed_date: "",
  proposed_time: "10:00:00",
  location: "",
  mode: "ONSITE" as AuditMode,
  marketing_remarks: "",
  scope_of_work: "",        // 🆕
  previous_cert_no: "",     // 🆕
};
const COORDINATOR_ROLE_ID = 5;
const SUPER_ADMIN_ROLE_ID = 1;
const SUPER_ADMIN_IDS = [1, 8];

function useIsCoordinatorOrAdmin(): boolean {
  const [allowed, setAllowed] = useState(false);
  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const raw = localStorage.getItem("user");
      const u = raw ? JSON.parse(raw) : null;
      const userId = Number(u?.id ?? u?.userId ?? u?.user_id);
      if (SUPER_ADMIN_IDS.includes(userId)) return setAllowed(true);

      const roles = Array.isArray(u?.roles) ? u.roles : (u?.user_roles ?? []);
      const roleIds = roles.map((r: any) => Number(r?.id ?? r?.role_id ?? r));
      const roleNames = roles.map((r: any) => String(r?.name ?? r).toLowerCase());

      setAllowed(
        roleIds.includes(COORDINATOR_ROLE_ID) ||
        roleIds.includes(SUPER_ADMIN_ROLE_ID) ||
        roleNames.some((n: string) => n.includes("coordinator") || n.includes("super")),
      );
    } catch {
      setAllowed(false);
    }
  }, []);
  return allowed;
}
// ─── Time helpers ──────────────────────────────────────────────────────────
const toTimeInput = (t: string): string => (t ? t.slice(0, 5) : "");
const toDbTime = (t: string): string =>
  t ? (t.length === 5 ? `${t}:00` : t) : "10:00:00";

// Base origin for serving uploaded files (strip the trailing "/api")
const FILE_ORIGIN = AUDIT_REQUESTS_API_BASE_URL.replace(/\/api\/?$/, "");

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

  // ── Form fields ─────────────────────────────────────────────────────────
  const [companyId, setCompanyId] = useState<number>(DEFAULTS.company_id);
  const [companyLabel, setCompanyLabel] = useState<string>("");
  const [pickedClient, setPickedClient] = useState<ClientSearchRow | null>(null);

  const [auditeeName, setAuditeeName] = useState(DEFAULTS.auditee_name);
  const [auditeeContact, setAuditeeContact] = useState(DEFAULTS.auditee_contact);
  const [auditeeEmail, setAuditeeEmail] = useState(DEFAULTS.auditee_email);
  const [auditees, setAuditees] = useState<{ name: string; designation: string }[]>([
    { name: "", designation: "" },
  ]);
  const [standardIds, setStandardIds] = useState<number[]>(DEFAULTS.standard_ids);
  const [certificationType, setCertificationType] = useState<CertificationType>(
    DEFAULTS.certification_type,
  );
  const [clientGroup, setClientGroup] = useState<"QRS" | "TQS">(DEFAULTS.client_group);
  const [accreditation, setAccreditation] = useState(DEFAULTS.accreditation);
  const [proposedDate, setProposedDate] = useState(DEFAULTS.proposed_date);
  const [proposedTime, setProposedTime] = useState(DEFAULTS.proposed_time);
  const [location, setLocation] = useState(DEFAULTS.location);
  const [mode, setMode] = useState<AuditMode>(DEFAULTS.mode);
  const [marketingRemarks, setMarketingRemarks] = useState(
    DEFAULTS.marketing_remarks,
  );
  // 🆕 Certification details — carried into the inquiry on Proceed
  const [scopeOfWork, setScopeOfWork] = useState(DEFAULTS.scope_of_work);
  const [previousCertNo, setPreviousCertNo] = useState(
    DEFAULTS.previous_cert_no,
  );
  const canEditStatus = useIsCoordinatorOrAdmin();
  const [status, setStatus] = useState<AuditRequestStatus>("SUBMITTED");
  // Newly-picked files (not yet uploaded)
  const [files, setFiles] = useState<File[]>([]);
  // 🆕 Mandatory typed documents — uploaded under their own form-data keys
  const [tradeLicenseFiles, setTradeLicenseFiles] = useState<File[]>([]);
  const [prevCertFiles, setPrevCertFiles] = useState<File[]>([]);
  // 🆕 append picks instead of replacing — lets the user attach MULTIPLE
  // previous certificates / licenses across several file-dialog picks.
  const appendTyped = (
    setter: React.Dispatch<React.SetStateAction<File[]>>,
    picked: File[],
  ) =>
    setter((prev) => [
      ...prev,
      ...picked.filter(
        (p) => !prev.some((f) => f.name === p.name && f.size === p.size),
      ),
    ]);
  // Already-saved documents loaded from the DB when editing
  const [existingDocs, setExistingDocs] = useState<StoredDoc[]>([]);

  // ── Lookup caches ───────────────────────────────────────────────────────
  const [standards, setStandards] = useState<StandardOpt[]>([]);

  // ── UI state ────────────────────────────────────────────────────────────
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);

  // ── Load standards once on open ─────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;

    fetchApi<StandardOpt[] | { data: StandardOpt[] }>(
      `${AUDIT_REQUESTS_API_BASE_URL}/standards`,
    )
      .then((res: any) => {
        const list = Array.isArray(res) ? res : (res?.data ?? []);
        setStandards(list);
      })
      .catch(() => setStandards([]));
  }, [isOpen]);

  // ── If editing, load the request ────────────────────────────────────────
  useEffect(() => {
    if (!isOpen || !editId) return;

    setLoading(true);
    getAuditRequest(editId)
      .then((r) => {
        // 🔎 debug — shows in browser console whether documents come back
        console.log("[EDIT-LOAD] documents →", (r as any).documents);

        setCompanyId(r.company_id ?? 0);
        // Company label falls back to the stored snapshot name when there
        // is no real company_id yet (submitted requests have only a name).
        setCompanyLabel(
          r.company
            ? `${r.company.name}${r.company.city ? ` (${r.company.city})` : ""}`
            : r.company_name ?? `Company #${r.company_id ?? ""}`,
        );
        setClientGroup((r as any).client_group ?? "QRS");
        setAuditeeName(r.auditee_name);
        setAuditeeContact(r.auditee_contact);
        setAuditeeEmail(r.auditee_email);
        setAuditees(
          (r as any).auditees?.length
            ? (r as any).auditees
            : [{ name: "", designation: "" }],
        );
        setStandardIds(r.standard_ids);
        setCertificationType(r.certification_type);
        setAccreditation(r.accreditation);
        setProposedDate(r.proposed_date);
        setProposedTime(r.proposed_time);
        setLocation(r.location);
        setMode(r.mode);
        setMarketingRemarks(r.marketing_remarks ?? "");
        setScopeOfWork((r as any).scope_of_work ?? "");           // 🆕
        setPreviousCertNo((r as any).previous_cert_no ?? "");     // 🆕
        setStatus((r as any).status ?? "SUBMITTED");
        // ✅ load already-uploaded documents so they show in the form
        setExistingDocs(
          Array.isArray((r as any).documents) ? (r as any).documents : [],
        );
      })
      .catch((err) => toast.error(err?.message || "Failed to load request"))
      .finally(() => setLoading(false));
  }, [isOpen, editId]);

  // ── Reset on close ──────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) {
      setCompanyId(DEFAULTS.company_id);
      setCompanyLabel("");
      setPickedClient(null);
      setAuditeeName(DEFAULTS.auditee_name);
      setAuditeeContact(DEFAULTS.auditee_contact);
      setAuditeeEmail(DEFAULTS.auditee_email);
      setAuditees([{ name: "", designation: "" }]);   // 🆕
      setStandardIds(DEFAULTS.standard_ids);
      setCertificationType(DEFAULTS.certification_type);
      setClientGroup(DEFAULTS.client_group);   // 🆕 add this
      setAccreditation(DEFAULTS.accreditation);
      setProposedDate(DEFAULTS.proposed_date);
      setProposedTime(DEFAULTS.proposed_time);
      setLocation(DEFAULTS.location);
      setMode(DEFAULTS.mode);
      setMarketingRemarks(DEFAULTS.marketing_remarks);
      setScopeOfWork(DEFAULTS.scope_of_work);          // 🆕
      setPreviousCertNo(DEFAULTS.previous_cert_no);    // 🆕
      setStatus("SUBMITTED");

      setFiles([]);
      setTradeLicenseFiles([]);   // 🆕
      setPrevCertFiles([]);       // 🆕
      setExistingDocs([]);
    }
  }, [isOpen]);

  // ── Async company search (scoped to the selected group's CRM DB) ────────
  const searchCompanies = useCallback(
    async (input: string): Promise<SelectOption[]> => {
      const q = input.trim();
      if (q.length < 10) return [];
      try {
        // 🆕 QRS / QRS_B → QRS database, TQS → TQS database
        const source = clientGroup === "TQS" ? "TQS" : "QRS";
        const res = await getClientsPagedAll({ search: q, limit: 20, source });
        const rows = mapClientsToSearchRows(res.rows ?? []);

        const qLower = q.toLowerCase();

        const exact = rows.filter(
          (c) => c.company_name.trim().toLowerCase() === qLower,
        );
        if (exact.length > 0) {
          return exact.map((c) => ({
            value: c.id,
            label:
              c.company_name +
              (c.Address ? ` — ${c.Address}` : "") +
              `  ·  ${c.client_type}`,
            raw: c,
          }));
        }

        const starts = rows.filter((c) =>
          c.company_name.toLowerCase().startsWith(qLower),
        );

        return starts.slice(0, 5).map((c) => ({
          value: c.id,
          label:
            c.company_name +
            (c.Address ? ` — ${c.Address}` : "") +
            `  ·  ${c.client_type}`,
          raw: c,
        }));
      } catch {
        return [];
      }
    },
    [clientGroup],   // 🆕 was []
  );
  // 🆕 auditee list helpers
  const addAuditee = () =>
    setAuditees((p) => [...p, { name: "", designation: "" }]);
  const removeAuditee = (i: number) =>
    setAuditees((p) => p.filter((_, idx) => idx !== i));
  const updateAuditee = (i: number, key: "name" | "designation", val: string) =>
    setAuditees((p) => p.map((a, idx) => (idx === i ? { ...a, [key]: val } : a)));

  const handleCompanyPick = async (opt: SelectOption | null) => {
    if (!opt) {
      setCompanyId(0);
      setCompanyLabel("");
      setPickedClient(null);
      return;
    }
    setCompanyId(Number(opt.value));
    setCompanyLabel(opt.label);
    setPickedClient(opt.raw ?? null);

    // 🆕 Auto-fill from old CRM — only fills EMPTY fields, stays editable
    try {
      const source = clientGroup === "TQS" ? "TQS" : "QRS";
      const type =
        opt.raw?.client_type === "Surveillance" ? "Surveillance" : "Client";

      const details = await getClientDetails(Number(opt.value), source, type);

      if (details) {
        if (!auditeeName && details.auditee_name)
          setAuditeeName(details.auditee_name);
        if (!auditeeContact && details.auditee_contact)
          setAuditeeContact(details.auditee_contact);
        if (!auditeeEmail && details.auditee_email)
          setAuditeeEmail(details.auditee_email);
        if (!location && details.location) setLocation(details.location);

        // fill first Auditees row if still blank + secondary contact from CRM
        setAuditees((prev) => {
          if (prev.length === 1 && !prev[0].name) {
            return [
              {
                name: details.auditee_name || "",
                designation: details.auditee_designation || "",
              },
              ...(details.auditees ?? []).map((a: any) => ({
                name: a.name || "",
                designation: a.designation || "",
              })),
            ];
          }
          return prev;
        });
        return; // CRM details found — skip the old fallback below
      }
    } catch {
      /* CRM lookup failed — fall through to old companies lookup */
    }

    // old fallback (kept, unchanged)
    try {
      const company = await fetchApi<CompanyOpt>(
        `${AUDIT_REQUESTS_API_BASE_URL}/companies/${opt.value}`,
      );
      if (company) {
        if (!auditeeName && company.contact_person)
          setAuditeeName(company.contact_person);
        if (!auditeeContact && company.mobile)
          setAuditeeContact(company.mobile);
        if (!auditeeEmail && company.email) setAuditeeEmail(company.email);
        if (!location && company.city) setLocation(company.city + ", UAE");
      }
    } catch {
      /* silent — pre-fill is best-effort */
    }
  };
  // ── Resolve a company name from its id (best-effort) ─────────────────────
  const resolveCompanyName = useCallback(async (id: number) => {
    if (!id) return;
    try {
      const company = await fetchApi<CompanyOpt>(
        `${AUDIT_REQUESTS_API_BASE_URL}/companies/${id}`,
      );
      if (company?.name) {
        setCompanyLabel(
          `${company.name}${company.city ? ` (${company.city})` : ""}`,
        );
      }
    } catch {
      /* silent — name lookup is best-effort */
    }
  }, []);

  // If we have an id but no label yet, fetch the name to display it
  useEffect(() => {
    if (isOpen && companyId && !companyLabel) {
      resolveCompanyName(companyId);
    }
  }, [isOpen, companyId, companyLabel, resolveCompanyName]);

  // ── Helper: upload picked files to a given request id ────────────────────
  const uploadFilesTo = async (requestId: number) => {
    // 🆕 typed uploads — matches the backend FileFieldsInterceptor keys.
    // Always call even with zero "other" files so the mandatory-document
    // check + submit email fire on the backend.
    if (
      !files.length &&
      !tradeLicenseFiles.length &&
      !prevCertFiles.length
    )
      return;
    const fd = new FormData();
    tradeLicenseFiles.forEach((f) => fd.append("trade_license", f));
    prevCertFiles.forEach((f) => fd.append("previous_certificate", f));
    files.forEach((f) => fd.append("files", f));

    const token =
      localStorage.getItem("token") ||
      localStorage.getItem("accessToken") ||
      localStorage.getItem("access_token");

    const res = await fetch(
      `${AUDIT_REQUESTS_API_BASE_URL}/audit-requests/${requestId}/upload-documents`,
      {
        method: "POST",
        headers: token ? { Authorization: `Bearer ${token}` } : undefined,
        body: fd, // no Content-Type — browser sets the multipart boundary
      },
    );
    // 🆕 surface the backend's mandatory-document error (400) to the user
    if (!res.ok) {
      let msg = "Document upload failed";
      try {
        const j = await res.json();
        msg = j?.message || msg;
      } catch { /* ignore parse errors */ }
      throw new Error(msg);
    }
  };

  // ── Submit ──────────────────────────────────────────────────────────────
  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();

    // ✅ FIX: only require a company when CREATING. On edit the company is
    // fixed (the select is disabled) and submitted requests may have a null
    // company_id, so skip this check in edit mode.
    if (!isEdit && !companyId)
      return toast.error("Please select a company");
    if (!auditeeName.trim()) return toast.error("Auditee name is required");
    if (!auditeeContact.trim())
      return toast.error("Auditee contact is required");
    if (!auditeeEmail.trim()) return toast.error("Auditee email is required");
    if (!standardIds.length) return toast.error("Select at least one standard");
    if (!proposedDate) return toast.error("Pick a proposed audit date");
    if (!location.trim()) return toast.error("Location is required");
    // 🆕 MANDATORY DOCUMENTS — mirrors the backend rule.
    // Trade License: always required. Previous Certificate: required unless
    // this is an INITIAL certification. Already-uploaded typed docs count in
    // edit mode; legacy untyped docs (no doc_type) also count so old
    // requests stay editable.
    const hasExisting = (t: string) =>
      existingDocs.some((d) => d.doc_type === t) ||
      existingDocs.some((d) => !d.doc_type); // legacy docs grandfathered
    if (tradeLicenseFiles.length === 0 && !hasExisting("trade_license")) {
      return toast.error("Trade License is required — please attach it.");
    }
    const needsPrevCert = certificationType !== "INITIAL";
    if (
      needsPrevCert &&
      prevCertFiles.length === 0 &&
      !hasExisting("previous_certificate")
    ) {
      return toast.error(
        "Previous Certificate is required for this certification type — please attach it.",
      );
    }

    setSubmitting(true);
    try {
      const cleanAuditees = auditees.filter((a) => a.name.trim());   // 🆕
      if (isEdit) {
        await updateAuditRequest(editId!, {
          status,
          client_group: clientGroup,
          auditee_name: auditeeName.trim(),
          auditee_contact: auditeeContact.trim(),
          auditee_email: auditeeEmail.trim(),
          auditees: cleanAuditees,   // 🆕
          standard_ids: standardIds,
          certification_type: certificationType,
          accreditation,
          proposed_date: proposedDate,
          proposed_time: proposedTime,
          location: location.trim(),
          mode,
          marketing_remarks: marketingRemarks.trim() || undefined,
          scope_of_work: scopeOfWork.trim() || undefined,        // 🆕
          previous_cert_no: previousCertNo.trim() || undefined,  // 🆕
        });

        // ✅ in edit mode, also upload any newly-picked files
        await uploadFilesTo(editId!);

        toast.success("Audit request updated.");
      } else {
        const dto: CreateAuditRequestDto = {
          company_name: pickedClient?.company_name ?? companyLabel,
          company_source: pickedClient?.client_type ?? "Client",
          client_group: clientGroup,   // 🆕 ADD THIS
          client_ref_id: pickedClient?.id ?? companyId,
          auditee_name: auditeeName.trim(),
          auditee_contact: auditeeContact.trim(),
          auditee_email: auditeeEmail.trim(),
          auditees: cleanAuditees,   // 🆕
          standard_ids: standardIds,
          certification_type: certificationType,
          accreditation,
          proposed_date: proposedDate,
          proposed_time: proposedTime,
          location: location.trim(),
          mode,
          marketing_remarks: marketingRemarks.trim() || undefined,
          scope_of_work: scopeOfWork.trim() || undefined,        // 🆕
          previous_cert_no: previousCertNo.trim() || undefined,  // 🆕
        };

        // 1) create → returns the new record (with id)
        const created = await createAuditRequest(dto);
        const newId = (created as any)?.id;

        // 2) upload files to the new id — this ALSO fires the submit email
        if (newId) await uploadFilesTo(newId);

        toast.success(
          "📋 Audit request submitted — the coordinator will review shortly.",
        );
      }
      refreshData?.();
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Failed to submit request");
    } finally {
      setSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 900, width: "95%" }}
      >
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>
              {isEdit ? "✏️ Edit Audit Request" : "＋ New Audit Request"}
            </h2>
            <p className={styles.modalSubtitle}>
              {isEdit
                ? "Update your audit request — coordinator will see the changes"
                : "Submit an audit request for client confirmation and scheduling"}
            </p>
          </div>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            type="button"
            aria-label="Close"
          >
            ✕
          </button>
        </div>

        {loading ? (
          <div style={{ padding: 60, textAlign: "center", color: "#9ca3af" }}>
            Loading request…
          </div>
        ) : (
          <form onSubmit={handleSubmit} className={styles.form}>
            <div className={styles.formBody}>
              {/* ══ Client Information ═══════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Client Information
              </div>

              <div className={styles.grid2}>
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Client
                  </label>
                  <AsyncSelect<SelectOption>
                    key={clientGroup}   // 🆕 reset cached results when group changes
                    classNamePrefix="rselect"
                    cacheOptions
                    defaultOptions={false}
                    loadOptions={searchCompanies}
                    // ✅ FIX: gate on the LABEL (not companyId) so the saved
                    // company name shows on edit even when company_id is null.
                    value={
                      companyLabel
                        ? { value: companyId || -1, label: companyLabel }
                        : null
                    }
                    onChange={(opt) =>
                      handleCompanyPick(opt as SelectOption | null)
                    }
                    placeholder="Type the full company name (min 10 chars)..."
                    noOptionsMessage={({ inputValue }) =>
                      inputValue.length < 10
                        ? `Type the full company name (${10 - inputValue.length} more chars needed)`
                        : `No company found matching "${inputValue}"`
                    }
                    loadingMessage={() => "Searching..."}
                    isClearable
                    isDisabled={isEdit}
                  />
                  {isEdit && (
                    <div
                      style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}
                    >
                      Company can't be changed after submission
                    </div>
                  )}
                </div>

                <div className={styles.formGroup}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Auditee Name
                  </label>
                  <input
                    type="text"
                    className={styles.input}
                    value={auditeeName}
                    onChange={(e) => setAuditeeName(e.target.value)}
                    placeholder="e.g., Mr. Azhar K Mohamed"
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Contact Number
                  </label>
                  <input
                    type="text"
                    className={styles.input}
                    value={auditeeContact}
                    onChange={(e) => setAuditeeContact(e.target.value)}
                    placeholder="e.g., +971 56 367 9416"
                  />
                </div>

                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Auditee Email
                  </label>
                  <input
                    type="email"
                    className={styles.input}
                    value={auditeeEmail}
                    onChange={(e) => setAuditeeEmail(e.target.value)}
                    placeholder="contact@company.com"
                  />
                </div>
              </div>
              {/* ══ Auditees / Attendees ═════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Auditees / Attendees
              </div>

              <div className={`${styles.formGroup} ${styles.full}`}>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {auditees.map((a, i) => (
                    <div key={i} style={{ display: "flex", gap: 8, alignItems: "center" }}>
                      <input
                        className={styles.input}
                        placeholder="Name"
                        value={a.name}
                        onChange={(e) => updateAuditee(i, "name", e.target.value)}
                        style={{ flex: 1 }}
                      />
                      <input
                        className={styles.input}
                        placeholder="Designation"
                        value={a.designation}
                        onChange={(e) => updateAuditee(i, "designation", e.target.value)}
                        style={{ flex: 1 }}
                      />
                      {auditees.length > 1 && (
                        <button
                          type="button"
                          onClick={() => removeAuditee(i)}
                          style={{
                            border: "1px solid #fca5a5",
                            background: "#fef2f2",
                            color: "#b91c1c",
                            borderRadius: 8,
                            padding: "9px 12px",
                            cursor: "pointer",
                          }}
                          title="Remove auditee"
                        >
                          ✕
                        </button>
                      )}
                    </div>
                  ))}
                  <button
                    type="button"
                    onClick={addAuditee}
                    style={{
                      alignSelf: "flex-start",
                      border: "1px dashed #c4b5fd",
                      background: "#f5f3ff",
                      color: "#6d28d9",
                      borderRadius: 8,
                      padding: "8px 14px",
                      cursor: "pointer",
                      fontWeight: 700,
                      fontSize: 13,
                    }}
                  >
                    + Add Auditee
                  </button>
                </div>
                <div style={{ marginTop: 6, fontSize: 11, color: "#9ca3af", lineHeight: 1.5 }}>
                  Add everyone from the client side who will attend the audit (e.g. Manager, QHSE
                  Officer, Engineer). Click <strong>+ Add Auditee</strong> for each person — the
                  auditor can adjust this list on the day. These names print on the attendance sheet.
                </div>
              </div>
              {/* ══ Group (QRS / TQS) ════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Group
              </div>

              <div className={`${styles.formGroup} ${styles.full}`}>
                <div style={{ display: "flex", gap: 10 }}>
                  {[
                    { value: "QRS", label: "QRS", icon: <Building2 size={16} strokeWidth={2} /> },
                    { value: "TQS", label: "TQS", icon: <Landmark size={16} strokeWidth={2} /> },
                    { value: "QRS_B", label: "QRS-B", icon: <Building2 size={16} strokeWidth={2} /> },

                  ].map((opt) => {
                    const active = clientGroup === opt.value;
                    return (
                      <button
                        type="button"
                        key={opt.value}
                        onClick={() => setClientGroup(opt.value as "QRS" | "TQS")}
                        style={{
                          flex: 1,
                          padding: "16px 14px",
                          borderRadius: 12,
                          cursor: "pointer",
                          fontSize: 14,
                          fontWeight: 700,
                          textAlign: "center",
                          border: active ? "2px solid #7c3aed" : "2px solid #e5e7eb",
                          background: active
                            ? "linear-gradient(135deg, #f5f3ff 0%, #ede9fe 100%)"
                            : "#fff",
                          color: active ? "#6d28d9" : "#6b7280",
                          transition: "all 0.2s ease",
                          boxShadow: active
                            ? "0 4px 12px rgba(124, 58, 237, 0.15)"
                            : "0 1px 2px rgba(0,0,0,0.04)",
                          transform: active ? "translateY(-1px)" : "none",
                          position: "relative",
                          display: "inline-flex",
                          alignItems: "center",
                          justifyContent: "center",
                          gap: 8,
                        }}
                      >
                        {opt.icon}
                        {opt.label}
                        {active && (
                          <span
                            style={{
                              position: "absolute",
                              top: 6,
                              right: 8,
                              color: "#7c3aed",
                              display: "inline-flex",
                            }}
                          >
                            <Check size={12} strokeWidth={3} />
                          </span>
                        )}
                      </button>
                    );
                  })}
                </div>
                <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                  Client search looks in the {clientGroup === "TQS" ? "TQS" : "QRS"} database
                </div>
              </div>
              {/* ══ Audit Scope ═════════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Audit Scope
              </div>

              <div className={styles.grid2}>
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Standards
                  </label>
                  <Select<SelectOption, true>
                    classNamePrefix="rselect"
                    isMulti
                    options={standards.map((s) => ({
                      value: s.id,
                      label: s.name,
                    }))}
                    value={
                      standardIds
                        .map((id) => {
                          const std = standards.find((s) => s.id === id);
                          return std ? { value: id, label: std.name } : null;
                        })
                        .filter(Boolean) as SelectOption[]
                    }
                    onChange={(opts) =>
                      setStandardIds((opts ?? []).map((o) => Number(o.value)))
                    }
                    placeholder="Pick one or more standards (e.g., ISO 9001:2015)"
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Certification Type
                  </label>
                  <Select<SelectOption>
                    classNamePrefix="rselect"
                    options={CERTIFICATION_TYPE_OPTIONS}
                    value={
                      CERTIFICATION_TYPE_OPTIONS.find(
                        (o) => o.value === certificationType,
                      ) ?? null
                    }
                    onChange={(opt) =>
                      setCertificationType(
                        (opt?.value as CertificationType) ?? "SURVEILLANCE_1",
                      )
                    }
                    isSearchable={false}
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Accreditation
                  </label>
                  <Select<SelectOption>
                    classNamePrefix="rselect"
                    options={ACCREDITATION_OPTIONS}
                    value={
                      ACCREDITATION_OPTIONS.find(
                        (o) => o.value === accreditation,
                      ) ?? null
                    }
                    onChange={(opt) =>
                      setAccreditation((opt?.value as string) ?? "ASCB")
                    }
                  />
                </div>
              </div>

              {/* ══ 🆕 Certification Details ═════════════════════════════
                  Carried into the inquiry automatically on Proceed and the
                  scope is saved onto the company record. */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Certification Details
              </div>

              <div className={`${styles.formGroup} ${styles.full}`}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Scope of Work
                </label>
                <textarea
                  className={styles.textarea}
                  rows={3}
                  value={scopeOfWork}
                  onChange={(e) => setScopeOfWork(e.target.value)}
                  placeholder="e.g., Manufacturing of wooden furniture and interior fit-out works for commercial and residential projects"
                />
                <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                  Printed on the certificate — carried into the inquiry and
                  saved to the company record
                </div>
              </div>

              <div className={styles.grid2}>
                <div className={styles.formGroup}>
                  <label className={styles.label}>
                    Previous Certificate No.
                  </label>
                  <input
                    type="text"
                    className={styles.input}
                    value={previousCertNo}
                    onChange={(e) => setPreviousCertNo(e.target.value)}
                    placeholder="e.g., QRS-14023-QM"
                  />
                  <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                    Leave blank for initial certification
                  </div>
                </div>
              </div>

              {/* ══ Proposed Schedule ═══════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Proposed Schedule
              </div>

              <div className={styles.grid2}>
                <div className={styles.formGroup}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Proposed Date
                  </label>
                  <input
                    type="date"
                    className={styles.input}
                    value={proposedDate}
                    onChange={(e) => setProposedDate(e.target.value)}
                    min={new Date().toISOString().split("T")[0]}
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Proposed Time</label>
                  <input
                    type="time"
                    className={styles.input}
                    value={toTimeInput(proposedTime)}
                    onChange={(e) => setProposedTime(toDbTime(e.target.value))}
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Location Details
                  </label>
                  <input
                    type="text"
                    className={styles.input}
                    value={location}
                    onChange={(e) => setLocation(e.target.value)}
                    placeholder="e.g., Dubai & Sharjah, UAE"
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={`${styles.label} ${styles.labelRequired}`}>
                    Audit Mode
                  </label>
                  <Select<SelectOption>
                    classNamePrefix="rselect"
                    options={AUDIT_MODE_OPTIONS}
                    value={
                      AUDIT_MODE_OPTIONS.find((o) => o.value === mode) ?? null
                    }
                    onChange={(opt) =>
                      setMode((opt?.value as AuditMode) ?? "ONSITE")
                    }
                    isSearchable={false}
                  />
                </div>
              </div>

              {/* ══ Supporting Documents ════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Supporting Documents (Trade License, etc.)
              </div>

              <div className={`${styles.formGroup} ${styles.full}`}>

                {/* Already-uploaded documents (edit mode) */}
                {existingDocs.length > 0 && (
                  <div style={{ marginBottom: 8 }}>
                    <div
                      style={{
                        fontSize: 11,
                        color: "#6b7280",
                        marginBottom: 4,
                        fontWeight: 600,
                      }}
                    >
                      Already uploaded:
                    </div>
                    <ul
                      style={{
                        margin: 0,
                        fontSize: 12,
                        color: "#0f172a",
                        paddingLeft: 18,
                      }}
                    >
                      {existingDocs.map((d, i) => (
                        <li key={i} style={{ marginBottom: 2 }}>
                          📎{" "}
                          <a
                            href={`${FILE_ORIGIN}/${d.path}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{
                              color: "#6d28d9",
                              textDecoration: "underline",
                            }}
                          >
                            {d.filename}
                          </a>{" "}
                          <span style={{ color: "#9ca3af" }}>
                            ({(d.size / 1024).toFixed(0)} KB)
                          </span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {/* 🆕 Typed mandatory documents — sent under their own
                    form-data keys (trade_license / previous_certificate) so
                    the backend can enforce that both are attached. */}
                <div className={styles.grid2}>
                  <div className={styles.formGroup}>
                    <label className={`${styles.label} ${styles.labelRequired}`}>
                      Trade License
                    </label>
                    <input
                      type="file"
                      multiple
                      accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.zip,.rar"
                      className={styles.input}
                      onChange={(e) => {
                        appendTyped(
                          setTradeLicenseFiles,
                          Array.from(e.target.files ?? []),
                        );
                        e.target.value = ""; // allow re-picking
                      }}
                    />
                    {tradeLicenseFiles.length > 0 && (
                      <ul style={{ marginTop: 6, fontSize: 11, color: "#0f766e", paddingLeft: 16 }}>
                        {tradeLicenseFiles.map((f, i) => (
                          <li key={i}>
                            {f.name} ({(f.size / 1024).toFixed(0)} KB)
                            <button
                              type="button"
                              onClick={() =>
                                setTradeLicenseFiles((prev) =>
                                  prev.filter((_, idx) => idx !== i),
                                )
                              }
                              style={{ marginLeft: 6, color: "#dc2626", border: "none", background: "none", cursor: "pointer" }}
                            >
                              ✕
                            </button>
                          </li>
                        ))}
                      </ul>
                    )}
                  </div>

                  <div className={styles.formGroup}>
                    <label
                      className={`${styles.label} ${
                        certificationType !== "INITIAL"
                          ? styles.labelRequired
                          : ""
                      }`}
                    >
                      Previous Certificate
                    </label>
                    <input
                      type="file"
                      multiple
                      accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.zip,.rar"
                      className={styles.input}
                      onChange={(e) => {
                        appendTyped(
                          setPrevCertFiles,
                          Array.from(e.target.files ?? []),
                        );
                        e.target.value = ""; // allow re-picking
                      }}
                    />
                    <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                      {certificationType === "INITIAL"
                        ? "Optional for initial certification"
                        : "Required for this certification type"}
                    </div>
                    {prevCertFiles.length > 0 && (
                      <ul style={{ marginTop: 6, fontSize: 11, color: "#0f766e", paddingLeft: 16 }}>
                        {prevCertFiles.map((f, i) => (
                          <li key={i}>
                            {f.name} ({(f.size / 1024).toFixed(0)} KB)
                            <button
                              type="button"
                              onClick={() =>
                                setPrevCertFiles((prev) =>
                                  prev.filter((_, idx) => idx !== i),
                                )
                              }
                              style={{ marginLeft: 6, color: "#dc2626", border: "none", background: "none", cursor: "pointer" }}
                            >
                              ✕
                            </button>
                          </li>
                        ))}
                      </ul>
                    )}
                  </div>
                </div>

                <label className={styles.label} style={{ marginTop: 8 }}>
                  Other Documents (optional)
                </label>
                <input
                  type="file"
                  multiple
                  accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.zip,.rar"
                  className={styles.input}
                  onChange={(e) => setFiles(Array.from(e.target.files ?? []))}
                />
                {/* Newly-picked files (not yet uploaded) */}
                {files.length > 0 && (
                  <ul
                    style={{
                      marginTop: 8,
                      fontSize: 12,
                      color: "#6d28d9",
                      paddingLeft: 18,
                    }}
                  >
                    {files.map((f, i) => (
                      <li key={i}>
                        {f.name} ({(f.size / 1024).toFixed(0)} KB)
                        <button
                          type="button"
                          onClick={() =>
                            setFiles((prev) =>
                              prev.filter((_, idx) => idx !== i),
                            )
                          }
                          style={{
                            marginLeft: 8,
                            color: "#dc2626",
                            border: "none",
                            background: "none",
                            cursor: "pointer",
                          }}
                        >
                          ✕
                        </button>
                      </li>
                    ))}
                  </ul>
                )}

                <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                  Trade License is always required; Previous Certificate is
                  required except for initial certification. PDF, JPG, PNG,
                  DOC, ZIP.
                </div>
              </div>

              {/* ══ Marketing Remarks ═══════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot}></span>
                Marketing Notes (Optional)
              </div>

              <div className={`${styles.formGroup} ${styles.full}`}>
                <label className={styles.label}>Marketing Remarks</label>
                <textarea
                  className={styles.textarea}
                  rows={3}
                  value={marketingRemarks}
                  onChange={(e) => setMarketingRemarks(e.target.value)}
                  placeholder="Any special requirements, client preferences, or context the coordinator should know about..."
                  maxLength={1000}
                />
                <div
                  style={{
                    marginTop: 4,
                    fontSize: 11,
                    color: "#9ca3af",
                    textAlign: "right",
                  }}
                >
                  {marketingRemarks.length}/1000
                </div>
              </div>
            </div>
            {/* ══ Status (Coordinator / Admin only) ════════════════════ */}
            {isEdit && (
              <div style={{ padding: "0 24px 16px" }}>
                <div className={styles.sectionHeader}>
                  <span className={styles.sectionDot}></span>
                  Status (Coordinator / Admin only)
                </div>
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>Request Status</label>
                  <select
                    className={styles.input}
                    value={status}
                    onChange={(e) => setStatus(e.target.value as AuditRequestStatus)}
                  >
                    <option value="DRAFT">Draft</option>
                    <option value="SUBMITTED">Submitted</option>
                    <option value="UNDER_REVIEW">Under Review</option>
                    <option value="SCHEDULED">Scheduled</option>
                    <option value="REJECTED">Rejected</option>
                    <option value="CANCELLED">Cancelled</option>
                    <option value="COMPLETED">Completed</option>
                  </select>
                </div>
              </div>
            )}
            {/* ── Footer ───────────────────────────────────────────────── */}
            <div className={styles.modalFooter}>
              <button
                type="button"
                className={styles.cancelBtn}
                onClick={onClose}
                disabled={submitting}
              >
                Cancel
              </button>
              <button
                type="submit"
                className={styles.saveBtn}
                disabled={submitting}
              >
                {submitting
                  ? "Submitting..."
                  : isEdit
                    ? "💾 Save Changes"
                    : "📋 Submit Request"}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}