"use client";

import React, { useEffect, useState } 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 {
  createInquiry,
  updateInquiry,
  getInquiry,
  INQUIRIES_API_BASE,
} from "@/lib/api/inquiry.api";
import { fetchApi } from "@/lib/api/http";
import type {
  CreateInquiryDto,
  InquiryType,
} from "@/lib/api/types/inquiry.types";

// CompanyForm modal — used for INITIAL inquiries with new clients
import CompanyForm from "./../../companies/Form/CompanyForm";

// ✅ NEW — real icons replacing emojis (no logic changes)
import {
  ClipboardList,
  Building2,
  Landmark,
  Calendar,
  FileText,
  StickyNote,
  Paperclip,
  TrafficCone,
  Undo2,
  FileSignature,
  Search as SearchIcon,
  RefreshCw,
  Sparkles,
  Upload,
  Trash2,
  X as XIcon,
  Check,
  CheckCircle2,
  AlertTriangle,
  Lightbulb,
  User,
  Mail,
  MapPin,
  Inbox,
  File as FileIcon,
  Pencil,
  Hourglass,
  Award,
  Mailbox,
  PenLine,
} from "lucide-react";

// ─── Types ────────────────────────────────────────────────────────────────────
interface SelectOption {
  value: number | string;
  label: string;
}

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

interface InquiryDocument {
  type: string;
  path: string;
  filename: string;
  uploaded_at: string;
  uploaded_by?: number;
}

interface PendingFile {
  file: File;
  type: string;
}

// ─── Default form state ───────────────────────────────────────────────────────
const DEFAULT = {
  inquiry_type: "SURVEILLANCE" as InquiryType,
  cert_body: "" as string,
  audit_stage: "" as string,
  company_id: undefined as number | undefined,
  audit_date: "",
  auditor_name: "",
  previous_cert_no: "",
  notes: "",
  standards: [] as number[],
  submitted_by_id: undefined as number | undefined,
  certificate_number: "",
  issue_date: "",
  expiry_date: "",
  surveillance_audit_due: "",
  recertification_due: "",
  accreditation_body: "",
  scope_of_work: "",
  change_request_notes: "",
};

// ✅ CHANGED — labels now plain text; icons render separately in the buttons
const TYPE_OPTIONS: { value: string; label: string; icon: React.ReactNode }[] = [
  {
    value: "SURVEILLANCE",
    label: "Surveillance",
    icon: <SearchIcon size={14} strokeWidth={2} />,
  },
  {
    value: "RE_CERTIFICATION",
    label: "Re-Certification",
    icon: <RefreshCw size={14} strokeWidth={2} />,
  },
  {
    value: "INITIAL",
    label: "New Client",
    icon: <Sparkles size={14} strokeWidth={2} />,
  },
];

// ✅ CHANGED — labels now plain text; icons render separately in the buttons
const CERT_BODY_OPTIONS: { value: string; label: string; icon: React.ReactNode }[] =
  [
    {
      value: "QRS",
      label: "QRS",
      icon: <Building2 size={16} strokeWidth={2} />,
    },
    {
      value: "TQS",
      label: "TQS",
      icon: <Landmark size={16} strokeWidth={2} />,
    },
  ];

const AUDIT_STAGE_OPTIONS: SelectOption[] = [
  { value: "Stage 1", label: "Stage 1" },
  { value: "Stage 2", label: "Stage 2" },
  { value: "Surveillance", label: "Surveillance" },
  { value: "Recertification", label: "Recertification" },
];

const STATUS_OPTIONS: SelectOption[] = [
  { value: "PENDING", label: "Pending" },
  { value: "IN_REVIEW", label: "In Review" },
  { value: "DRAFT_READY", label: "Draft Ready" },
  { value: "CHANGES_REQUESTED", label: "Changes Requested" },
  { value: "CLIENT_CONFIRMED", label: "Client Confirmed" },
  { value: "FINAL_ISSUED", label: "Final Issued" },
];

const SCHEME_STATUSES = [
  "IN_REVIEW",
  "DRAFT_READY",
  "CHANGES_REQUESTED",
  "CLIENT_CONFIRMED",
  "FINAL_ISSUED",
];

// ✅ CHANGED — labels now plain; icons rendered in the doc list/select via helper below
const DOC_TYPE_OPTIONS: { value: string; label: string }[] = [
  { value: "trade_license", label: "Trade License" },
  { value: "previous_certificate", label: "Previous Certificate" },
  { value: "audit_report", label: "Audit Report" },
  { value: "scope_letter", label: "Scope Letter" },
  { value: "other", label: "Other" },
];

const docTypeLabel = (t: string) =>
  DOC_TYPE_OPTIONS.find((o) => o.value === t)?.label ?? t;

// ─── Reusable Form Section component ─────────────────────────────────────────
// ✅ CHANGED — `icon` prop is now ReactNode (was string)
function FormSection({
  icon,
  title,
  subtitle,
  children,
  variant = "default",
}: {
  icon: React.ReactNode;
 title: React.ReactNode; 
  subtitle?: string;
  children: React.ReactNode;
  variant?: "default" | "warning" | "danger";
}) {
  const palette = {
    default: {
      dot: "#0f766e",
      text: "#0f172a",
      bg: "transparent",
      border: "transparent",
    },
    warning: {
      dot: "#f59e0b",
      text: "#92400e",
      bg: "#fffbeb",
      border: "#fde68a",
    },
    danger: {
      dot: "#ef4444",
      text: "#991b1b",
      bg: "#fef2f2",
      border: "#fecaca",
    },
  }[variant];

  return (
    <div
      style={{
        marginTop: 22,
        padding: variant !== "default" ? "16px 18px" : "0",
        backgroundColor: palette.bg,
        borderRadius: variant !== "default" ? 10 : 0,
        border:
          variant !== "default" ? `1px solid ${palette.border}` : undefined,
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 10,
          marginBottom: 14,
          paddingBottom: variant === "default" ? 10 : 0,
          borderBottom: variant === "default" ? "1px solid #e5e7eb" : undefined,
        }}
      >
        <span
          style={{
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            width: 30,
            height: 30,
            borderRadius: 8,
            backgroundColor: `${palette.dot}15`,
            color: palette.dot,
            fontSize: 15,
          }}
        >
          {icon}
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h3
            style={{
              margin: 0,
              fontSize: 13,
              fontWeight: 700,
              color: palette.text,
              letterSpacing: "0.03em",
              textTransform: "uppercase",
            }}
          >
            {title}
          </h3>
          {subtitle && (
            <p
              style={{
                margin: "2px 0 0",
                fontSize: 11,
                color: "#9ca3af",
                fontWeight: 400,
              }}
            >
              {subtitle}
            </p>
          )}
        </div>
      </div>
      {children}
    </div>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────
export default function InquiryForm({
  isOpen,
  onClose,
  refreshData,
  editId,
}: Props) {
  const isEdit = Boolean(editId);

  const [form, setForm] = useState({ ...DEFAULT });
  const [status, setStatus] = useState<string>("PENDING");
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [saving, setSaving] = useState<boolean>(false);
  const [loadingEdit, setLoadingEdit] = useState<boolean>(false);
  const [standardsList, setStandardsList] = useState<SelectOption[]>([]);
  const [dropdownLoading, setDropdownLoading] = useState<boolean>(false);
  const [selectedCompany, setSelectedCompany] = useState<SelectOption | null>(
    null,
  );
  const [companyInfo, setCompanyInfo] = useState<{
    contact_person: string;
    email: string;
    city: string;
    standards: { id: number; name: string }[];
  } | null>(null);

  const [showCompanyForm, setShowCompanyForm] = useState<boolean>(false);

  // Documents state
  const [existingDocs, setExistingDocs] = useState<InquiryDocument[]>([]);
  const [pendingFiles, setPendingFiles] = useState<PendingFile[]>([]);
  const [uploading, setUploading] = useState<boolean>(false);

  // ── AsyncSelect: search companies server-side ──────────────────────────────
  const loadCompanyOptions = async (
    inputValue: string,
  ): Promise<SelectOption[]> => {
    const query = inputValue.trim();
    if (query.length < 10) return [];

    try {
      const res = await fetchApi<any>(
        `${INQUIRIES_API_BASE}/companies?limit=10&search=${encodeURIComponent(query)}`,
      );
      const companies = res?.data ?? res ?? [];

      const queryLower = query.toLowerCase();

      const filtered = companies.filter(
        (c: any) => c.name && c.name.toLowerCase().startsWith(queryLower),
      );

      return filtered.slice(0, 5).map((c: any) => ({
        value: c.id,
        label: c.name,
      }));
    } catch {
      return [];
    }
  };

  // ── Load standards ─────────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    setDropdownLoading(true);
    fetchApi<any[]>(`${INQUIRIES_API_BASE}/standards`)
      .then((standards) => {
        setStandardsList(
          (standards ?? []).map((s: any) => ({
            value: s.id,
            label: `${s.name} — ${s.title}`,
          })),
        );
      })
      .catch(() => toast.error("Failed to load standards"))
      .finally(() => setDropdownLoading(false));
  }, [isOpen]);

  // ── Hydrate on edit ────────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getInquiry(editId)
        .then((inq) => {
          setForm({
            inquiry_type: inq.inquiry_type,
            cert_body: (inq as any).cert_body || "",
            audit_stage: (inq as any).audit_stage || "",
            company_id: inq.company?.id,
            audit_date: inq.audit_date || "",
            auditor_name: inq.auditor_name || "",
            previous_cert_no: inq.previous_cert_no || "",
            notes: inq.notes || "",
            standards: inq.standards?.map((s) => s.id) ?? [],
            submitted_by_id: inq.submitted_by?.id,
            certificate_number: inq.certificate_number || "",
            issue_date: inq.issue_date || "",
            expiry_date: inq.expiry_date || "",
            surveillance_audit_due: (inq as any).surveillance_audit_due || "",
            recertification_due: (inq as any).recertification_due || "",
            accreditation_body: inq.accreditation_body || "",
            scope_of_work: inq.scope_of_work || "",
            change_request_notes: inq.change_request_notes || "",
          });
          setStatus(inq.status);
          setExistingDocs(((inq as any).documents as InquiryDocument[]) ?? []);
          setPendingFiles([]);
          if (inq.company) {
            setSelectedCompany({
              value: inq.company.id,
              label: inq.company.name,
            });
            setCompanyInfo({
              contact_person: inq.company.contact_person,
              email: inq.company.email,
              city: inq.company.city,
              standards: inq.company.standards ?? [],
            });
          }
        })
        .catch(() => toast.error("Failed to load inquiry"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT });
      setStatus("PENDING");
      setErrors({});
      setTouched({});
      setCompanyInfo(null);
      setSelectedCompany(null);
      setExistingDocs([]);
      setPendingFiles([]);
    }
  }, [isOpen, editId]);

  // ── Company selected → auto-fill ───────────────────────────────────────────
  const handleCompanySelect = async (sel: SelectOption | null) => {
    if (!sel) {
      setForm((p) => ({ ...p, company_id: undefined, standards: [] }));
      setSelectedCompany(null);
      setCompanyInfo(null);
      return;
    }
    setSelectedCompany(sel);
    setForm((p) => ({ ...p, company_id: Number(sel.value) }));
    setTouched((p) => ({ ...p, company_id: true }));
    setErrors((p) => ({ ...p, company_id: "" }));
    try {
      const company = await fetchApi<any>(
        `${INQUIRIES_API_BASE}/companies/${sel.value}`,
      );
      setCompanyInfo({
        contact_person: company.contact_person,
        email: company.email,
        city: company.city,
        standards: company.standards ?? [],
      });
      setForm((p) => ({
        ...p,
        standards: (company.standards ?? []).map((s: any) => s.id),
        scope_of_work: company.scope_of_work || p.scope_of_work,
      }));
    } catch {
      /* non-critical */
    }
  };

  const showErr = (key: string) => !!(errors[key] && touched[key]);
  const field = (key: keyof typeof form) => (val: string) => {
    setForm((p) => ({ ...p, [key]: val }));
    setTouched((p) => ({ ...p, [key]: true }));
    setErrors((p) => ({ ...p, [key]: "" }));
  };

  const showSchemeFields = isEdit && SCHEME_STATUSES.includes(status);
  const certRequired = status === "IN_REVIEW" || status === "DRAFT_READY";
  const showChangeRequestField = isEdit && status === "CHANGES_REQUESTED";

  // ── Validate ───────────────────────────────────────────────────────────────
  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.company_id) e.company_id = "Company is required";
    if (!form.inquiry_type) e.inquiry_type = "Type is required";
    if (!form.cert_body || !String(form.cert_body).trim())
      e.cert_body = "Group is required";
    if (!form.audit_date) e.audit_date = "Audit date is required";
    if (!form.auditor_name.trim()) e.auditor_name = "Auditor name is required";
    if (certRequired) {
      if (!form.certificate_number.trim())
        e.certificate_number = "Required before generating draft";
      if (!form.issue_date) e.issue_date = "Required before generating draft";
      if (!form.expiry_date) e.expiry_date = "Required before generating draft";
    }
    setErrors(e);
    setTouched((p) => ({
      ...p,
      ...Object.fromEntries(Object.keys(e).map((k) => [k, true])),
    }));
    return Object.keys(e).length === 0;
  };

  // ── Submit ─────────────────────────────────────────────────────────────────
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setSaving(true);
    try {
      let userId: number | undefined;
      try {
        const token = localStorage.getItem("access_token");
        if (token) {
          const payload = JSON.parse(atob(token.split(".")[1]));
          userId = payload?.sub ?? payload?.id ?? payload?.userId;
          if (userId) userId = Number(userId);
        }
      } catch {
        /* ignore */
      }

      if (isEdit && editId) {
        // ✅ DEBUG — Track update flow
        console.log('═══════════════════════════════════════════════');
        console.log('📝 [UPDATE INQUIRY] Updating inquiry ID:', editId);
        console.log('   📊 Status changing to:', status);
        console.log('   📁 Pending files to upload:', pendingFiles.length);
        console.log('═══════════════════════════════════════════════');

        await updateInquiry(editId, {
          inquiry_type: form.inquiry_type,
          audit_date: form.audit_date,
          auditor_name: form.auditor_name,
          cert_body: (form.cert_body || undefined) as any,
          audit_stage: (form.audit_stage || undefined) as any,
          previous_cert_no: form.previous_cert_no,
          notes: form.notes,
          standards: form.standards,
          status: status as any,
          certificate_number: form.certificate_number || undefined,
          issue_date: form.issue_date || undefined,
          expiry_date: form.expiry_date || undefined,
          surveillance_audit_due: form.surveillance_audit_due || undefined,
          recertification_due: form.recertification_due || undefined,
          accreditation_body: form.accreditation_body || undefined,
          scope_of_work: form.scope_of_work || undefined,
          change_request_notes: form.change_request_notes || undefined,
        } as any);

        console.log('✅ [UPDATE INQUIRY] Inquiry updated successfully');

        // ✅ NEW — Upload pending documents during EDIT (in case user added files but didn't click upload button)
        if (pendingFiles.length > 0) {
          console.log('📤 [UPDATE INQUIRY] Auto-uploading pending files on update...');
          try {
            const token = localStorage.getItem("access_token");
            const formData = new FormData();
            pendingFiles.forEach((pf: PendingFile) =>
              formData.append("files", pf.file),
            );
            formData.append(
              "types",
              JSON.stringify(pendingFiles.map((p: PendingFile) => p.type)),
            );
            const uploadUrl = `${INQUIRIES_API_BASE}/inquiries/${editId}/upload-documents`;
            console.log('🌐 [UPDATE INQUIRY] Uploading to:', uploadUrl);
            const uploadRes = await fetch(uploadUrl, {
              method: "POST",
              headers: { Authorization: `Bearer ${token}` },
              body: formData,
            });
            console.log('📨 [UPDATE INQUIRY] Upload response status:', uploadRes.status);
            if (uploadRes.ok) {
              console.log('✅ [UPDATE INQUIRY] Documents uploaded successfully');
              toast.success(`Inquiry updated & ${pendingFiles.length} file(s) uploaded`);
            } else {
              console.error('❌ [UPDATE INQUIRY] Upload failed:', uploadRes.status);
              toast.success("Inquiry updated");
              toast.error("Documents could not be uploaded.");
            }
          } catch (uploadErr) {
            console.error('❌ [UPDATE INQUIRY] Upload exception:', uploadErr);
            toast.success("Inquiry updated");
            toast.error("Documents could not be uploaded.");
          }
        } else {
          toast.success("Inquiry updated successfully");
        }
      } else {
        // ✅ DEBUG — Track create flow
        console.log('═══════════════════════════════════════════════');
        console.log('🆕 [CREATE INQUIRY] Creating new inquiry');
        console.log('   👤 Submitter ID (from JWT):', userId);
        console.log('   📁 Pending files to upload:', pendingFiles.length);
        console.log('═══════════════════════════════════════════════');

        const newInquiry: any = await createInquiry({
          inquiry_type: form.inquiry_type,
          company_id: form.company_id!,
          audit_date: form.audit_date,
          auditor_name: form.auditor_name,
          cert_body: (form.cert_body || undefined) as any,
          audit_stage: (form.audit_stage || undefined) as any,
          previous_cert_no: form.previous_cert_no,
          notes: form.notes,
          standards: form.standards,
          submitted_by_id: userId,
        } as any);

        console.log('📦 [CREATE INQUIRY] Backend response:', newInquiry);
        console.log('   🆔 New Inquiry ID:', newInquiry?.id);
        console.log('   🔖 Inquiry Ref:', newInquiry?.inquiry_ref);

        // Auto-upload pending documents using the new inquiry's id
        if (pendingFiles.length > 0 && newInquiry?.id) {
          console.log('📤 [CREATE INQUIRY] Starting document upload for inquiry ID:', newInquiry.id);
          try {
            const token = localStorage.getItem("access_token");
            console.log('🔑 [CREATE INQUIRY] Token present?', !!token);

            const formData = new FormData();
            pendingFiles.forEach((pf: PendingFile) =>
              formData.append("files", pf.file),
            );
            formData.append(
              "types",
              JSON.stringify(pendingFiles.map((p: PendingFile) => p.type)),
            );

            const uploadUrl = `${INQUIRIES_API_BASE}/inquiries/${newInquiry.id}/upload-documents`;
            console.log('🌐 [CREATE INQUIRY] Uploading to:', uploadUrl);

            const res = await fetch(uploadUrl, {
              method: "POST",
              headers: { Authorization: `Bearer ${token}` },
              body: formData,
            });

            console.log('📨 [CREATE INQUIRY] Upload response status:', res.status, res.statusText);

            if (res.ok) {
              const responseData = await res.json();
              console.log('✅ [CREATE INQUIRY] Upload succeeded:', responseData);
              toast.success(
                `Inquiry created & ${pendingFiles.length} document(s) uploaded`,
              );
            } else {
              const errorText = await res.text();
              console.error('❌ [CREATE INQUIRY] Upload failed:', res.status, errorText);
              toast.success("Inquiry created");
              toast.error("Documents could not be uploaded. Edit to retry.");
            }
          } catch (uploadErr) {
            console.error('❌ [CREATE INQUIRY] Upload exception:', uploadErr);
            toast.success("Inquiry created");
            toast.error("Documents could not be uploaded. Edit to retry.");
          }
        } else {
          console.log('⚠️ [CREATE INQUIRY] No files to upload or no inquiry ID');
          console.log('   pendingFiles.length:', pendingFiles.length);
          console.log('   newInquiry?.id:', newInquiry?.id);
          toast.success("Inquiry created successfully");
        }
      }
      onClose();
      refreshData?.();
    } catch (err: any) {
      console.error('❌ [SUBMIT ERROR]:', err);
      toast.error(err?.message ?? "Failed to save inquiry.");
    } finally {
      setSaving(false);
    }
  };

  // Upload pending files to backend (edit mode immediate upload)
  const handleUploadFiles = async () => {
    if (!editId || pendingFiles.length === 0) return;
    setUploading(true);
    try {
      const token = localStorage.getItem("access_token");
      const formData = new FormData();
      pendingFiles.forEach((pf: PendingFile) =>
        formData.append("files", pf.file),
      );
      formData.append(
        "types",
        JSON.stringify(pendingFiles.map((p: PendingFile) => p.type)),
      );

      console.log('📤 [MANUAL UPLOAD] Uploading files for inquiry:', editId);

      const res = await fetch(
        `${INQUIRIES_API_BASE}/inquiries/${editId}/upload-documents`,
        {
          method: "POST",
          headers: { Authorization: `Bearer ${token}` },
          body: formData,
        },
      );

      console.log('📨 [MANUAL UPLOAD] Response:', res.status);

      if (!res.ok) throw new Error(`Upload failed: HTTP ${res.status}`);
      const data = await res.json();

      console.log('✅ [MANUAL UPLOAD] Success:', data);

      setExistingDocs(data.documents ?? []);
      setPendingFiles([]);
      toast.success(`${data.count} document(s) uploaded`);
      refreshData?.();
    } catch (err: any) {
      console.error("❌ [MANUAL UPLOAD] Error:", err);
      toast.error(err?.message ?? "Upload failed");
    } finally {
      setUploading(false);
    }
  };

  // Delete a document by index
  const handleDeleteDoc = async (index: number) => {
    if (!editId) return;
    if (!confirm("Delete this document? This cannot be undone.")) return;
    try {
      const token = localStorage.getItem("access_token");
      const res = await fetch(
        `${INQUIRIES_API_BASE}/inquiries/${editId}/documents/${index}`,
        {
          method: "DELETE",
          headers: { Authorization: `Bearer ${token}` },
        },
      );
      if (!res.ok) throw new Error("Delete failed");
      const data = await res.json();
      setExistingDocs(data.documents ?? []);
      toast.success("Document deleted");
      refreshData?.();
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to delete document");
    }
  };

  if (!isOpen) return null;

  const selStandards = standardsList.filter((s) =>
    form.standards.includes(Number(s.value)),
  );
  const selStatus = STATUS_OPTIONS.find((o) => o.value === status) ?? null;

  // Pro-style reusable input look
  const inputStyle: React.CSSProperties = {
    width: "100%",
    padding: "10px 14px",
    fontSize: 13,
    borderRadius: 8,
    border: "1.5px solid #e5e7eb",
    backgroundColor: "#fff",
    color: "#0f172a",
    boxSizing: "border-box",
    outline: "none",
    transition: "all 0.15s",
  };
  const labelStyle: React.CSSProperties = {
    display: "block",
    fontSize: 12,
    fontWeight: 600,
    color: "#374151",
    marginBottom: 6,
  };
  const errorTextStyle: React.CSSProperties = {
    marginTop: 4,
    fontSize: 12,
    color: "#ef4444",
    fontWeight: 500,
  };
  const requiredMark = (
    <span style={{ color: "#ef4444", marginLeft: 2 }}>*</span>
  );

  return (
    <>
      {/* CompanyForm modal on top, only for INITIAL type */}
      <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 }) => {
            handleCompanySelect({
              value: newCompany.id,
              label: newCompany.name,
            });
            setShowCompanyForm(false);
          }}
        />
      </div>

      <div className={styles.modalOverlay} onClick={onClose}>
        <div
          className={styles.modalContent}
          onClick={(e) => e.stopPropagation()}
          style={{
            maxWidth: 820,
            maxHeight: "90vh",
            overflow: "hidden",
            padding: 0,
          }}
        >
          {/* ═══ Gradient Header ═══ */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              padding: "20px 28px",
              background: isEdit
                ? "linear-gradient(135deg, #0f766e 0%, #0891b2 100%)"
                : "linear-gradient(135deg, #1e40af 0%, #2563eb 100%)",
              color: "#fff",
            }}
          >
            <div>
              <p
                style={{
                  margin: "0 0 4px",
                  fontSize: 11,
                  fontWeight: 600,
                  letterSpacing: "0.08em",
                  textTransform: "uppercase",
                  color: "rgba(255,255,255,0.75)",
                }}
              >
                {isEdit ? "Edit Inquiry" : "New Inquiry"}
              </p>
              <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>
                {isEdit
                  ? "Update Certification Inquiry"
                  : "Submit Certification Inquiry"}
              </h2>
            </div>
            <button
              onClick={onClose}
              type="button"
              style={{
                width: 34,
                height: 34,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                borderRadius: 8,
                border: "none",
                background: "rgba(255,255,255,0.2)",
                color: "#fff",
                cursor: "pointer",
                fontSize: 16,
                fontWeight: 700,
              }}
            >
              <XIcon size={18} strokeWidth={2.5} />
            </button>
          </div>

          {loadingEdit ? (
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 12,
                padding: 60,
                color: "#9ca3af",
                fontSize: 14,
              }}
            >
              <div
                style={{
                  width: 28,
                  height: 28,
                  border: "3px solid #e5e7eb",
                  borderTopColor: "#0f766e",
                  borderRadius: "50%",
                  animation: "spin 0.7s linear infinite",
                }}
              />
              Loading inquiry data...
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              <div
                style={{
                  padding: "4px 28px 24px",
                  maxHeight: "calc(90vh - 160px)",
                  overflowY: "auto",
                }}
              >
                {/* ═══ INQUIRY TYPE ═══ */}
                <FormSection
                  icon={<ClipboardList size={16} strokeWidth={2} />}
                  title="Inquiry Type"
                  subtitle="Select the certification type"
                >
                  <div style={{ display: "flex", gap: 10 }}>
                    {TYPE_OPTIONS.map((opt) => {
                      const active = form.inquiry_type === opt.value;
                      return (
                        <button
                          type="button"
                          key={opt.value}
                          onClick={() => {
                            setForm((p) => ({
                              ...p,
                              inquiry_type: opt.value as InquiryType,
                            }));
                            setTouched((p) => ({ ...p, inquiry_type: true }));
                          }}
                          style={{
                            flex: 1,
                            padding: "12px 10px",
                            borderRadius: 10,
                            cursor: "pointer",
                            fontSize: 13,
                            fontWeight: 600,
                            textAlign: "center",
                            border: active
                              ? "2px solid #2563eb"
                              : "2px solid #e5e7eb",
                            backgroundColor: active ? "#eff6ff" : "#fff",
                            color: active ? "#2563eb" : "#6b7280",
                            transition: "all 0.15s",
                            boxShadow: active
                              ? "0 2px 8px rgba(37, 99, 235, 0.15)"
                              : "none",
                            display: "inline-flex",
                            alignItems: "center",
                            justifyContent: "center",
                            gap: 6,
                          }}
                        >
                          {opt.icon}
                          {opt.label}
                        </button>
                      );
                    })}
                  </div>
                </FormSection>

               {/* ═══ GROUP (formerly Certification Body) — REQUIRED ═══ */}
                <FormSection
                  icon={<Landmark size={16} strokeWidth={2} />}
                  title={
                    <>
                      Group <span style={{ color: "#ef4444" }}>*</span>
                    </>
                  }
                  subtitle="Which group is this audit conducted under?"
                >
                  <div style={{ display: "flex", gap: 10 }}>
                    {CERT_BODY_OPTIONS.map((opt) => {
                      const active = form.cert_body === opt.value;
                      const hasError = showErr("cert_body") && !form.cert_body;
                      return (
                        <button
                          type="button"
                          key={opt.value}
                          onClick={() => {
                            setForm((p) => ({
                              ...p,
                              cert_body: opt.value as string,
                            }));
                            setTouched((p) => ({ ...p, cert_body: true }));
                            setErrors((p) => ({ ...p, cert_body: "" })); // ✅ NEW — clear error on selection
                          }}
                          style={{
                            flex: 1,
                            padding: "16px 14px",
                            borderRadius: 12,
                            cursor: "pointer",
                            fontSize: 14,
                            fontWeight: 700,
                            textAlign: "center",
                            // ✅ UPDATED — show red border when validation fails
                            border: active
                              ? "2px solid #7c3aed"
                              : hasError
                                ? "2px solid #ef4444"
                                : "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,
                                fontSize: 11,
                                color: "#7c3aed",
                                fontWeight: 800,
                                display: "inline-flex",
                              }}
                            >
                              <Check size={12} strokeWidth={3} />
                            </span>
                          )}
                        </button>
                      );
                    })}
                  </div>
                  {/* ✅ NEW — error message below buttons when not selected */}
                  {showErr("cert_body") && (
                    <div style={errorTextStyle}>{errors.cert_body}</div>
                  )}
                </FormSection>
                {/* ═══ COMPANY ═══ */}
                <FormSection
                  icon={<Building2 size={16} strokeWidth={2} />}
                  title="Company"
                  subtitle={
                    isEdit
                      ? "Locked — cannot be changed"
                      : "Select existing or add new"
                  }
                >
                  <label style={labelStyle}>
                    Search Company {requiredMark}
                  </label>
                  <AsyncSelect
                    classNamePrefix="rselect"
                    loadOptions={loadCompanyOptions}
                    value={selectedCompany}
                    onChange={(sel) =>
                      handleCompanySelect(sel as SelectOption | null)
                    }
                    isDisabled={isEdit}
                    isSearchable
                    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..."}
                    styles={{
                      control: (b: any) => ({
                        ...b,
                        borderColor: showErr("company_id")
                          ? "#ef4444"
                          : "#e5e7eb",
                        borderRadius: 8,
                        minHeight: 42,
                        boxShadow: "none",
                      }),
                    }}
                  />
                  {showErr("company_id") && (
                    <div style={errorTextStyle}>{errors.company_id}</div>
                  )}

                  {/* Add New Company button — only for INITIAL */}
                  {!isEdit &&
                    form.inquiry_type === "INITIAL" &&
                    !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",
                        }}
                      >
                        + Add New Company
                      </button>
                    )}

                  {/* Auto-filled info card */}
                  {companyInfo && (
                    <div
                      style={{
                        marginTop: 12,
                        padding: "12px 14px",
                        backgroundColor: "#eff6ff",
                        border: "1px solid #bfdbfe",
                        borderRadius: 8,
                      }}
                    >
                      <div
                        style={{
                          fontSize: 11,
                          fontWeight: 700,
                          color: "#1e40af",
                          textTransform: "uppercase",
                          letterSpacing: "0.05em",
                          marginBottom: 6,
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                        <CheckCircle2 size={13} strokeWidth={2} />
                        Company Auto-Filled
                      </div>
                      <div
                        style={{
                          fontSize: 12,
                          color: "#1e40af",
                          display: "flex",
                          flexWrap: "wrap",
                          gap: 14,
                        }}
                      >
                        <span
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 4,
                          }}
                        >
                          <User size={12} strokeWidth={2} />
                          {companyInfo.contact_person || "—"}
                        </span>
                        <span
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 4,
                          }}
                        >
                          <Mail size={12} strokeWidth={2} />
                          {companyInfo.email || "—"}
                        </span>
                        <span
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 4,
                          }}
                        >
                          <MapPin size={12} strokeWidth={2} />
                          {companyInfo.city || "—"}
                        </span>
                      </div>
                    </div>
                  )}
                </FormSection>

                {/* ═══ AUDIT DETAILS ═══ */}
                <FormSection
                  icon={<Calendar size={16} strokeWidth={2} />}
                  title="Audit Details"
                  subtitle="When and who conducted the audit"
                >
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "1fr 1fr",
                      gap: 14,
                    }}
                  >
                    <div>
                      <label style={labelStyle}>
                        Audit Date {requiredMark}
                      </label>
                      <input
                        type="date"
                        value={form.audit_date}
                        onChange={(e) => field("audit_date")(e.target.value)}
                        style={{
                          ...inputStyle,
                          borderColor: showErr("audit_date")
                            ? "#ef4444"
                            : "#e5e7eb",
                        }}
                      />
                      {showErr("audit_date") && (
                        <div style={errorTextStyle}>{errors.audit_date}</div>
                      )}
                    </div>
                    <div>
                      <label style={labelStyle}>
                        Auditor Name {requiredMark}
                      </label>
                      <input
                        type="text"
                        value={form.auditor_name}
                        placeholder="e.g. MR. HASSAN AL MALIK"
                        onChange={(e) => field("auditor_name")(e.target.value)}
                        style={{
                          ...inputStyle,
                          borderColor: showErr("auditor_name")
                            ? "#ef4444"
                            : "#e5e7eb",
                        }}
                      />
                      {showErr("auditor_name") && (
                        <div style={errorTextStyle}>{errors.auditor_name}</div>
                      )}
                    </div>

                    {/* ✅ Audit Stage dropdown */}
                    <div style={{ gridColumn: "span 2" }}>
                      <label style={labelStyle}>
                        Audit Stage
                        <span
                          style={{
                            marginLeft: 8,
                            fontSize: 10,
                            fontWeight: 600,
                            color: "#7c3aed",
                            background: "#f5f3ff",
                            padding: "2px 8px",
                            borderRadius: 10,
                            textTransform: "uppercase",
                            letterSpacing: "0.05em",
                          }}
                        >
                          For Scheme Dept
                        </span>
                      </label>
                      <Select
                        classNamePrefix="rselect"
                        options={AUDIT_STAGE_OPTIONS}
                        value={
                          AUDIT_STAGE_OPTIONS.find(
                            (o) => o.value === form.audit_stage,
                          ) || null
                        }
                        onChange={(sel) =>
                          setForm((p) => ({
                            ...p,
                            audit_stage:
                              ((sel as SelectOption | null)?.value as string) ||
                              "",
                          }))
                        }
                        isClearable
                        isSearchable={false}
                        placeholder="Select audit stage..."
                        styles={{
                          control: (b: any, s: any) => ({
                            ...b,
                            borderRadius: 8,
                            minHeight: 42,
                            borderColor: s.isFocused ? "#7c3aed" : "#e5e7eb",
                            boxShadow: s.isFocused
                              ? "0 0 0 3px rgba(124, 58, 237, 0.1)"
                              : "none",
                            "&:hover": { borderColor: "#7c3aed" },
                          }),
                          option: (b: any, s: any) => ({
                            ...b,
                            backgroundColor: s.isSelected
                              ? "#7c3aed"
                              : s.isFocused
                                ? "#f5f3ff"
                                : "#fff",
                            color: s.isSelected ? "#fff" : "#0f172a",
                            fontWeight: s.isSelected ? 600 : 400,
                          }),
                        }}
                      />
                      <div
                        style={{
                          marginTop: 6,
                          fontSize: 11,
                          color: "#9ca3af",
                          display: "flex",
                          alignItems: "center",
                          gap: 4,
                        }}
                      >
                        <Lightbulb size={12} strokeWidth={2} />
                        Tells Scheme dept which stage this scope summary is for
                      </div>
                    </div>

                    <div style={{ gridColumn: "span 2" }}>
                      <label style={labelStyle}>Previous Certificate No.</label>
                      <input
                        type="text"
                        value={form.previous_cert_no}
                        placeholder="e.g. UAE-AB-QMS-D084R"
                        onChange={(e) =>
                          field("previous_cert_no")(e.target.value)
                        }
                        style={{ ...inputStyle, fontFamily: "monospace" }}
                      />
                    </div>
                  </div>
                </FormSection>

                {/* ═══ ISO STANDARDS ═══ */}
                <FormSection
                  icon={<FileText size={16} strokeWidth={2} />}
                  title="ISO Standards"
                  subtitle="Auto-filled from company. Edit if needed."
                >
                  <Select
                    classNamePrefix="rselect"
                    isMulti
                    options={standardsList}
                    value={selStandards}
                    onChange={(sel) =>
                      setForm((p) => ({
                        ...p,
                        standards: sel.map((s) => Number(s.value)),
                      }))
                    }
                    isLoading={dropdownLoading}
                    placeholder="Search and select standards..."
                    noOptionsMessage={() => "No standards found"}
                    closeMenuOnSelect={false}
                    styles={{
                      control: (b: any) => ({
                        ...b,
                        borderRadius: 8,
                        minHeight: 42,
                        boxShadow: "none",
                      }),
                    }}
                  />
                </FormSection>

                {/* ═══ NOTES ═══ */}
                <FormSection
                  icon={<StickyNote size={16} strokeWidth={2} />}
                  title="Notes"
                  subtitle="Additional info, scope changes, special requirements"
                >
                  <textarea
                    value={form.notes}
                    rows={3}
                    placeholder="Any additional info from the client email..."
                    onChange={(e) =>
                      setForm((p) => ({ ...p, notes: e.target.value }))
                    }
                    style={{
                      ...inputStyle,
                      resize: "vertical",
                      fontFamily: "inherit",
                    }}
                  />
                </FormSection>

                {/* ═══ SUPPORTING DOCUMENTS — visible in BOTH create + edit ═══ */}
                <FormSection
                  icon={<Paperclip size={16} strokeWidth={2} />}
                  title="Supporting Documents"
                  subtitle="Trade license, previous certificate, audit report, etc."
                >
                  {/* Existing uploaded documents (only in edit mode) */}
                  {isEdit && existingDocs.length > 0 && (
                    <div
                      style={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 8,
                        marginBottom: 12,
                      }}
                    >
                      {existingDocs.map((doc, idx) => (
                        <div
                          key={idx}
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 12,
                            padding: "10px 14px",
                            backgroundColor: "#f0fdfa",
                            border: "1px solid #99f6e4",
                            borderRadius: 8,
                          }}
                        >
                          <span
                            style={{
                              fontSize: 11,
                              fontWeight: 700,
                              padding: "4px 10px",
                              borderRadius: 6,
                              backgroundColor: "#0f766e",
                              color: "#fff",
                              whiteSpace: "nowrap",
                            }}
                          >
                            {docTypeLabel(doc.type)}
                          </span>
                          <span
                            style={{
                              flex: 1,
                              color: "#0f766e",
                              fontWeight: 600,
                              fontSize: 13,
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                              whiteSpace: "nowrap",
                            }}
                            title={doc.filename}
                          >
                            {doc.filename}
                          </span>
                          <span style={{ fontSize: 11, color: "#6b7280" }}>
                            {new Date(doc.uploaded_at).toLocaleDateString(
                              "en-GB",
                              {
                                day: "2-digit",
                                month: "short",
                                year: "numeric",
                              },
                            )}
                          </span>
                          <button
                            type="button"
                            onClick={() => handleDeleteDoc(idx)}
                            style={{
                              padding: "5px 12px",
                              borderRadius: 6,
                              border: "1px solid #fca5a5",
                              backgroundColor: "#fef2f2",
                              color: "#dc2626",
                              cursor: "pointer",
                              fontSize: 12,
                              fontWeight: 600,
                              display: "inline-flex",
                              alignItems: "center",
                              gap: 4,
                            }}
                          >
                            <Trash2 size={12} strokeWidth={2} />
                            Delete
                          </button>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* File picker (large dashed button) */}
                  <label
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: 8,
                      padding: "16px",
                      borderRadius: 10,
                      cursor: "pointer",
                      fontSize: 13,
                      fontWeight: 600,
                      border: "2px dashed #14b8a6",
                      backgroundColor: "#f0fdfa",
                      color: "#0f766e",
                    }}
                  >
                    <Upload size={18} strokeWidth={2} />
                    <span>Click to choose files</span>
                    <span
                      style={{
                        fontSize: 11,
                        fontWeight: 400,
                        color: "#6b7280",
                      }}
                    >
                      (Max 10 files, 10MB each)
                    </span>
                    <input
                      type="file"
                      multiple
                      style={{ display: "none" }}
                      onChange={(e) => {
                        const files = Array.from(e.target.files ?? []);
                        setPendingFiles((prev: PendingFile[]) => [
                          ...prev,
                          ...files.map((f) => ({
                            file: f,
                            type: "trade_license",
                          })),
                        ]);
                        e.target.value = "";
                      }}
                    />
                  </label>

                  {/* Pending files (waiting to upload) */}
                  {pendingFiles.length > 0 && (
                    <div
                      style={{
                        marginTop: 12,
                        padding: 14,
                        backgroundColor: "#fffbeb",
                        border: "1px solid #fde68a",
                        borderRadius: 8,
                      }}
                    >
                      <div
                        style={{
                          fontSize: 12,
                          fontWeight: 700,
                          color: "#92400e",
                          marginBottom: 8,
                          letterSpacing: "0.02em",
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                        <Inbox size={14} strokeWidth={2} />
                        {pendingFiles.length} file(s) ready to upload
                      </div>
                      <div
                        style={{
                          display: "flex",
                          flexDirection: "column",
                          gap: 6,
                        }}
                      >
                        {pendingFiles.map((pf: PendingFile, i: number) => (
                          <div
                            key={i}
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: 8,
                              padding: "8px 10px",
                              backgroundColor: "#fff",
                              borderRadius: 6,
                              border: "1px solid #fde68a",
                              fontSize: 13,
                            }}
                          >
                            <FileIcon size={14} strokeWidth={2} />
                            <span
                              style={{
                                flex: 1,
                                fontWeight: 600,
                                color: "#374151",
                                overflow: "hidden",
                                textOverflow: "ellipsis",
                                whiteSpace: "nowrap",
                              }}
                              title={pf.file.name}
                            >
                              {pf.file.name}
                            </span>
                            <span style={{ fontSize: 11, color: "#9ca3af" }}>
                              {(pf.file.size / 1024).toFixed(1)} KB
                            </span>
                            <select
                              value={pf.type}
                              onChange={(e) => {
                                const t = e.target.value;
                                setPendingFiles((prev: PendingFile[]) =>
                                  prev.map((p: PendingFile, j: number) =>
                                    j === i ? { ...p, type: t } : p,
                                  ),
                                );
                              }}
                              style={{
                                padding: "5px 8px",
                                borderRadius: 6,
                                border: "1px solid #d1d5db",
                                fontSize: 12,
                                backgroundColor: "#fff",
                                cursor: "pointer",
                              }}
                            >
                              {DOC_TYPE_OPTIONS.map((t) => (
                                <option key={t.value} value={t.value}>
                                  {t.label}
                                </option>
                              ))}
                            </select>
                            <button
                              type="button"
                              onClick={() =>
                                setPendingFiles((prev: PendingFile[]) =>
                                  prev.filter(
                                    (_: PendingFile, j: number) => j !== i,
                                  ),
                                )
                              }
                              style={{
                                padding: "5px 10px",
                                borderRadius: 6,
                                border: "1px solid #fca5a5",
                                backgroundColor: "#fef2f2",
                                color: "#dc2626",
                                cursor: "pointer",
                                fontSize: 12,
                                fontWeight: 600,
                                display: "inline-flex",
                                alignItems: "center",
                              }}
                            >
                              <XIcon size={12} strokeWidth={2.5} />
                            </button>
                          </div>
                        ))}
                      </div>

                      {isEdit ? (
                        <button
                          type="button"
                          onClick={handleUploadFiles}
                          disabled={uploading}
                          style={{
                            marginTop: 10,
                            padding: "10px 18px",
                            borderRadius: 8,
                            border: "none",
                            backgroundColor: uploading ? "#9ca3af" : "#0f766e",
                            color: "#fff",
                            cursor: uploading ? "not-allowed" : "pointer",
                            fontSize: 13,
                            fontWeight: 700,
                            width: "100%",
                            display: "inline-flex",
                            alignItems: "center",
                            justifyContent: "center",
                            gap: 8,
                          }}
                        >
                          {uploading ? (
                            <>
                              <Hourglass size={14} strokeWidth={2} />
                              Uploading...
                            </>
                          ) : (
                            <>
                              <Upload size={14} strokeWidth={2} />
                              Upload {pendingFiles.length} file(s) now
                            </>
                          )}
                        </button>
                      ) : (
                        <div
                          style={{
                            marginTop: 10,
                            padding: "10px 12px",
                            backgroundColor: "#eff6ff",
                            border: "1px solid #bfdbfe",
                            borderRadius: 6,
                            fontSize: 11,
                            color: "#1e40af",
                            fontWeight: 500,
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 6,
                          }}
                        >
                          <Lightbulb size={12} strokeWidth={2} />
                          These files will upload automatically when you submit
                          the inquiry
                        </div>
                      )}
                    </div>
                  )}
                </FormSection>

                {/* ═══ STATUS (edit only) ═══ */}
                {isEdit && (
                  <FormSection
                    icon={<TrafficCone size={16} strokeWidth={2} />}
                    title="Workflow Status"
                    subtitle="Current pipeline stage"
                  >
                    <Select
                      classNamePrefix="rselect"
                      options={STATUS_OPTIONS}
                      value={selStatus}
                      onChange={(sel) =>
                        setStatus((sel?.value as string) ?? "PENDING")
                      }
                      isSearchable={false}
                      placeholder="Select status..."
                      styles={{
                        control: (b: any) => ({
                          ...b,
                          borderRadius: 8,
                          minHeight: 42,
                          boxShadow: "none",
                        }),
                      }}
                    />
                  </FormSection>
                )}

                {/* ═══ CHANGE REQUEST NOTES — only when status = CHANGES_REQUESTED ═══ */}
                {showChangeRequestField && (
                  <FormSection
                    icon={<Undo2 size={16} strokeWidth={2} />}
                    title="Change Request Notes"
                    subtitle="What changes does Marketing want?"
                    variant="danger"
                  >
                    <textarea
                      value={form.change_request_notes}
                      rows={3}
                      placeholder="e.g. Update the address, change ISO 45001 to ISO 9001, fix expiry date..."
                      onChange={(e) =>
                        setForm((p) => ({
                          ...p,
                          change_request_notes: e.target.value,
                        }))
                      }
                      style={{
                        ...inputStyle,
                        resize: "vertical",
                        fontFamily: "inherit",
                        borderColor: "#fecaca",
                      }}
                    />
                  </FormSection>
                )}

                {/* ═══ CERTIFICATE FIELDS (Scheme only) ═══ */}
                {showSchemeFields && (
                  <FormSection
                    icon={<FileSignature size={16} strokeWidth={2} />}
                    title="Certificate Details"
                    subtitle={
                      certRequired
                        ? "Required to generate draft"
                        : "Fill before generating"
                    }
                    variant="warning"
                  >
                    {certRequired && !form.certificate_number && (
                      <div
                        style={{
                          marginBottom: 14,
                          padding: "10px 14px",
                          backgroundColor: "#fef3c7",
                          border: "1px solid #fcd34d",
                          borderRadius: 8,
                          fontSize: 12,
                          color: "#92400e",
                          fontWeight: 500,
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                        <AlertTriangle size={13} strokeWidth={2} />
                        Fill all certificate fields below before clicking{" "}
                        <strong>&nbsp;Generate Draft</strong>
                      </div>
                    )}
                    {certRequired &&
                      form.certificate_number &&
                      form.issue_date &&
                      form.expiry_date && (
                        <div
                          style={{
                            marginBottom: 14,
                            padding: "10px 14px",
                            backgroundColor: "#f0fdf4",
                            border: "1px solid #a7f3d0",
                            borderRadius: 8,
                            fontSize: 12,
                            color: "#065f46",
                            fontWeight: 500,
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 6,
                          }}
                        >
                          <CheckCircle2 size={13} strokeWidth={2} />
                          Certificate details complete — Save then Generate
                          Draft
                        </div>
                      )}

                    <div
                      style={{
                        display: "grid",
                        gridTemplateColumns: "1fr 1fr",
                        gap: 14,
                      }}
                    >
                      <div style={{ gridColumn: "span 2" }}>
                        <label style={labelStyle}>
                          Certificate Number {certRequired && requiredMark}
                        </label>
                        <input
                          type="text"
                          value={form.certificate_number}
                          placeholder="e.g. UAE-AB-QMS-D084R / S1"
                          onChange={(e) =>
                            field("certificate_number")(e.target.value)
                          }
                          style={{
                            ...inputStyle,
                            fontFamily: "monospace",
                            borderColor: showErr("certificate_number")
                              ? "#ef4444"
                              : "#e5e7eb",
                          }}
                        />
                        {showErr("certificate_number") && (
                          <div style={errorTextStyle}>
                            {errors.certificate_number}
                          </div>
                        )}
                      </div>
                      <div>
                        <label style={labelStyle}>
                          Issue Date {certRequired && requiredMark}
                        </label>
                        <input
                          type="date"
                          value={form.issue_date}
                          onChange={(e) => field("issue_date")(e.target.value)}
                          style={{
                            ...inputStyle,
                            borderColor: showErr("issue_date")
                              ? "#ef4444"
                              : "#e5e7eb",
                          }}
                        />
                        {showErr("issue_date") && (
                          <div style={errorTextStyle}>{errors.issue_date}</div>
                        )}
                      </div>
                      <div>
                        <label style={labelStyle}>
                          Expiry Date {certRequired && requiredMark}
                        </label>
                        <input
                          type="date"
                          value={form.expiry_date}
                          onChange={(e) => field("expiry_date")(e.target.value)}
                          style={{
                            ...inputStyle,
                            borderColor: showErr("expiry_date")
                              ? "#ef4444"
                              : "#e5e7eb",
                          }}
                        />
                        {showErr("expiry_date") && (
                          <div style={errorTextStyle}>{errors.expiry_date}</div>
                        )}
                      </div>
                      {/* ✅ Surveillance Audit Due */}
                      <div>
                        <label style={labelStyle}>
                          Surv. Audit On or Before
                        </label>
                        <input
                          type="date"
                          value={form.surveillance_audit_due}
                          onChange={(e) =>
                            field("surveillance_audit_due" as any)(
                              e.target.value,
                            )
                          }
                          style={inputStyle}
                        />
                        <div
                          style={{
                            marginTop: 4,
                            fontSize: 11,
                            color: "#9ca3af",
                          }}
                        >
                          Prints as <strong>SURV. AUDIT ON OR BEFORE</strong> on
                          the certificate
                        </div>
                      </div>

                      {/* ✅ Re-certification Due */}
                      <div>
                        <label style={labelStyle}>
                          Re-certification Due On
                        </label>
                        <input
                          type="date"
                          value={form.recertification_due}
                          onChange={(e) =>
                            field("recertification_due" as any)(e.target.value)
                          }
                          style={inputStyle}
                        />
                        <div
                          style={{
                            marginTop: 4,
                            fontSize: 11,
                            color: "#9ca3af",
                          }}
                        >
                          Prints as <strong>RE-CERTIFICATION DUE ON</strong> on
                          the certificate
                        </div>
                      </div>
                      <div style={{ gridColumn: "span 2" }}>
                        <label style={labelStyle}>EA Code</label>
                        <input
                          type="text"
                          value={form.accreditation_body}
                          placeholder="e.g. 17 etc"
                          onChange={(e) =>
                            field("accreditation_body")(e.target.value)
                          }
                          style={inputStyle}
                        />
                      </div>
                      <div style={{ gridColumn: "span 2" }}>
                        <label style={labelStyle}>Scope of Work</label>
                        <textarea
                          value={form.scope_of_work}
                          rows={3}
                          placeholder="e.g. Retail sale of house furniture and furnishing articles..."
                          onChange={(e) =>
                            setForm((p) => ({
                              ...p,
                              scope_of_work: e.target.value,
                            }))
                          }
                          style={{
                            ...inputStyle,
                            resize: "vertical",
                            fontFamily: "inherit",
                          }}
                        />
                      </div>
                    </div>
                  </FormSection>
                )}

                {/* Hint for new inquiries */}
                {!isEdit && (
                  <div
                    style={{
                      marginTop: 22,
                      padding: "12px 14px",
                      backgroundColor: "#f0f9ff",
                      border: "1px solid #bae6fd",
                      borderRadius: 8,
                      fontSize: 12,
                      color: "#0c4a6e",
                      lineHeight: 1.5,
                      display: "inline-flex",
                      alignItems: "flex-start",
                      gap: 6,
                    }}
                  >
                    <Lightbulb
                      size={14}
                      strokeWidth={2}
                      style={{ marginTop: 1, flexShrink: 0 }}
                    />
                    <span>
                      <strong>Next step:</strong> After creating, Scheme will
                      edit this inquiry to fill certificate details and generate
                      the draft.
                    </span>
                  </div>
                )}
              </div>

              {/* ═══ Footer ═══ */}
              <div
                style={{
                  display: "flex",
                  justifyContent: "flex-end",
                  gap: 10,
                  padding: "16px 28px",
                  borderTop: "1px solid #e5e7eb",
                  backgroundColor: "#f9fafb",
                }}
              >
                <button
                  type="button"
                  onClick={onClose}
                  style={{
                    padding: "10px 20px",
                    borderRadius: 8,
                    border: "1px solid #e5e7eb",
                    backgroundColor: "#fff",
                    color: "#6b7280",
                    cursor: "pointer",
                    fontSize: 13,
                    fontWeight: 600,
                  }}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={saving}
                  style={{
                    padding: "10px 24px",
                    borderRadius: 8,
                    border: "none",
                    background: saving
                      ? "#9ca3af"
                      : "linear-gradient(135deg, #0f766e 0%, #0891b2 100%)",
                    color: "#fff",
                    cursor: saving ? "not-allowed" : "pointer",
                    fontSize: 13,
                    fontWeight: 700,
                    boxShadow: saving
                      ? "none"
                      : "0 2px 8px rgba(15, 118, 110, 0.25)",
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  {saving ? (
                    <>
                      <Hourglass size={14} strokeWidth={2} />
                      {isEdit ? "Updating..." : "Saving..."}
                    </>
                  ) : (
                    <>
                      <Check size={14} strokeWidth={2.5} />
                      {isEdit ? "Update Inquiry" : "Submit Inquiry"}
                    </>
                  )}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </>
  );
}