"use client";

import React, { useEffect, useState, useCallback, useRef } from "react";
import Select from "react-select";
import AsyncSelect from "react-select/async";
import toast from "react-hot-toast";
import styles from "../../../modules/commonstyle/FormStyles.module.css";
import {
  createCompanyAudit,
  updateCompanyAudit,
  getCompanyAudit,
  getAuditorOptions,
} from "@/lib/api/companyAudit.api";
import { AUDIT_STAGES_API_BASE_URL } from "@/lib/api/auditStage.api";
import { fetchApi } from "@/lib/api/http";
import type { AuditStatus } from "@/lib/api/types/companyAudit.types";

// ─── Types ────────────────────────────────────────────────────────────────────
interface SelectOption { value: number | string; label: string; }
type FormTab = "companyInfo" | "scheduleAudit" | "auditStages";

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

// ─── Defaults — field names match the React version exactly ───────────────────
const DEFAULT_AUDIT = {
  company_id:     undefined as number | undefined,
  auditTypeId:    undefined as number | undefined,
  standardIds:    [] as number[],
  validityPeriod: "",
  auditMode:      "Physical" as string,
  currentStage:   "Stage 1" as string,
  remarks:        "",
  status:         "Scheduled" as string,
};

// Stage form — matches React AuditTabsModal exactly
const DEFAULT_STAGE_FORM = {
  auditId:         undefined as number | undefined,   // "Select Audit" dropdown
  stageName:       "Stage 1",
  auditDate:       "",
  auditById:       undefined as number | undefined,
  technicalExpert: "",
  anzicCode:       "",
  remarks:         "",
};

// ─── Static options ───────────────────────────────────────────────────────────
const AUDIT_STATUS_OPTIONS: SelectOption[] = [
  { value: "Scheduled",  label: "Scheduled"  },
  { value: "Ongoing",    label: "Ongoing"    },
  { value: "Completed",  label: "Completed"  },
  { value: "Cancelled",  label: "Cancelled"  },
];

const AUDIT_MODE_OPTIONS: SelectOption[] = [
  { value: "Physical", label: "Physical" },
  { value: "Online",   label: "Online"   },
  { value: "Hybrid",   label: "Hybrid"   },
];

const STAGE_NAMES = ["Stage 1", "Stage 2", "Surveillance", "Recertification"];

const statusColors: Record<string, { bg: string; dot: string }> = {
  Scheduled:  { bg: "#eff6ff", dot: "#1d4ed8" },
  Ongoing:    { bg: "#fefce8", dot: "#854d0e" },
  Completed:  { bg: "#f0fdf4", dot: "#166534" },
  Cancelled:  { bg: "#fef2f2", dot: "#991b1b" },
};

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

// ─── Component ────────────────────────────────────────────────────────────────
export default function CompanyAuditForm({
  isOpen, onClose, refreshData, editId,
  preselectedCompanyId, preselectedCompanyName,
}: Props) {
  const isEdit = Boolean(editId);
  const [activeTab, setActiveTab] = useState<FormTab>("companyInfo");

  // ── Form state ──────────────────────────────────────────────────────────────
  const [form, setForm]               = useState({ ...DEFAULT_AUDIT });
  const [errors, setErrors]           = useState<Record<string, string>>({});
  const [saving, setSaving]           = useState(false);
  const [loadingEdit, setLoadingEdit] = useState(false);

  // ── Dropdown options ─────────────────────────────────────────────────────────
  const [auditTypeOpts, setAuditTypeOpts]       = useState<SelectOption[]>([]);   // /audit-types
  const [standardOpts, setStandardOpts]         = useState<SelectOption[]>([]);   // /standards
  const [auditorOpts, setAuditorOpts]           = useState<SelectOption[]>([]);   // /users
  const [companyAuditOpts, setCompanyAuditOpts] = useState<SelectOption[]>([]);   // /company-audits?companyId=X
  const [dropdownsLoading, setDropdownsLoading] = useState(false);

  // ── Company info card (Tab 1) ─────────────────────────────────────────────
  const [companyInfo, setCompanyInfo]       = useState<any>(null);
  const [companyLoading, setCompanyLoading] = useState(false);

  // ── Audit stages (Tab 3) ─────────────────────────────────────────────────
  const [stageForm, setStageForm]           = useState({ ...DEFAULT_STAGE_FORM });
  const [savingStage, setSavingStage]       = useState(false);
  const [currentAuditId, setCurrentAuditId]   = useState<number | null>(null);
  // Mirrors React's `latestAudit` — used to auto-fill auditId + stageName on tab switch
  const [latestAuditData, setLatestAuditData] = useState<any>(null);

  // ── Debounce ref for AsyncSelect ──────────────────────────────────────────
  const debounceRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  // ─────────────────────────────────────────────────────────────────────────────
  // AsyncSelect loader — GET /companies?search=<term>&limit=30 (debounced 350ms)
  // ─────────────────────────────────────────────────────────────────────────────
  const loadCompanyOptions = useCallback(
    (inputValue: string): Promise<SelectOption[]> =>
      new Promise((resolve) => {
        clearTimeout(debounceRef.current);
        debounceRef.current = setTimeout(async () => {
          try {
            const query = new URLSearchParams({ limit: "30", page: "1" });
            if (inputValue.trim()) query.set("search", inputValue.trim());
            const res = await fetchApi<any>(`${API_BASE}/companies?${query}`);
            const arr: any[] = Array.isArray(res) ? res : (res?.data ?? []);
            resolve(arr.map((c) => ({
              value: c.id,
              label: c.name
                ? `${c.name}${c.company_code ? ` (${c.company_code})` : ""}`
                : String(c.id),
            })));
          } catch { resolve([]); }
        }, 350);
      }),
    []
  );

  // ── Load audit types, standards, auditors on open ────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    setDropdownsLoading(true);
    Promise.all([
      fetchApi<any>(`${API_BASE}/audit-types`),
      fetchApi<any>(`${API_BASE}/standards`),
      getAuditorOptions(),
    ])
      .then(([auditTypes, standards, auditors]) => {
        const typesArr = Array.isArray(auditTypes) ? auditTypes : (auditTypes?.data ?? []);
        const stdsArr  = Array.isArray(standards)  ? standards  : (standards?.data  ?? []);
        setAuditTypeOpts(typesArr.map((t: any) => ({ value: t.id,       label: t.name })));
        setStandardOpts(stdsArr.map((s: any)  => ({ value: Number(s.id), label: s.name })));
        setAuditorOpts(auditors);
      })
      .catch(() => toast.error("Failed to load dropdown data"))
      .finally(() => setDropdownsLoading(false));
  }, [isOpen]);

  // ── Hydrate on edit ─────────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getCompanyAudit(editId)
        .then((a: any) => {
          setForm({
            company_id:     a.company?.id,
            auditTypeId:    a.auditType?.id   ?? a.audit_type?.id,
            standardIds:    Array.isArray(a.standards)
              ? a.standards.map((s: any) => s.id ?? s)
              : [],
            validityPeriod: a.validityPeriod  ?? "",
            auditMode:      a.auditMode       ?? "Physical",
            currentStage:   a.currentStage    ?? "Stage 1",
            remarks:        a.remarks         ?? "",
            status:         a.status          ?? "Scheduled",
          });
          setCompanyInfo(a.company);
          setCurrentAuditId(editId);
          if (a.company?.id) fetchCompanyAudits(a.company.id);
        })
        .catch(() => toast.error("Failed to load audit data"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT_AUDIT, company_id: preselectedCompanyId || undefined });
      setErrors({});
      setCurrentAuditId(null);
      setCompanyAuditOpts([]);
      setStageForm({ ...DEFAULT_STAGE_FORM });
      setActiveTab("companyInfo");
      if (preselectedCompanyId) {
        fetchCompanyInfo(preselectedCompanyId);
        fetchCompanyAudits(preselectedCompanyId);
      } else {
        setCompanyInfo(null);
      }
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, editId]);

  // ── Fetch full company details (company info card) ────────────────────────
  const fetchCompanyInfo = useCallback(async (companyId: number) => {
    setCompanyLoading(true);
    try {
      const res = await fetchApi<any>(`${API_BASE}/companies/${companyId}`);
      setCompanyInfo(res);
    } catch { setCompanyInfo(null); }
    finally { setCompanyLoading(false); }
  }, []);

  // ── Fetch audits for the selected company → populates "Select Audit" in Tab 3
  const fetchCompanyAudits = useCallback(async (companyId: number) => {
    try {
      const res = await fetchApi<any>(`${API_BASE}/company-audits?companyId=${companyId}&limit=100`);
      const arr: any[] = Array.isArray(res) ? res : (res?.data ?? []);
      const opts = arr.map((a: any) => ({
        value: a.id,
        label: `Audit #${a.id}`,
      }));
      setCompanyAuditOpts(opts);

      // ✅ Mirrors React `latestAudit` — auto-select the most recently created audit
      if (arr.length > 0) {
        // Sort by id descending so we always get the true latest
        const sorted = [...arr].sort((a, b) => b.id - a.id);
        const latest = sorted[0];
        setLatestAuditData(latest);
        setStageForm((p) => ({
          ...p,
          auditId:   latest.id,
          stageName: latest.currentStage || "Stage 1",  // pre-fill from audit's currentStage
        }));
        setCurrentAuditId(latest.id);
      }
    } catch {
      setCompanyAuditOpts([]);
    }
  }, []);

  // ✅ Mirrors React: auto-set auditId + stageName whenever tab switches to "auditStages"
  useEffect(() => {
    if (activeTab === "auditStages" && latestAuditData) {
      setStageForm((prev) => ({
        ...prev,
        auditId:   latestAuditData.id,
        stageName: latestAuditData.currentStage || "Stage 1",
      }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab, latestAuditData]);

  // ── Validate ──────────────────────────────────────────────────────────────
  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.company_id)  e.company_id  = "Company is required";
    if (!form.auditTypeId) e.auditTypeId = "Audit type is required";
    if (!form.standardIds.length) e.standardIds = "Select at least one standard";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  // ── Submit: Schedule Audit — same payload shape as React ──────────────────
  const handleSubmitAudit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!validate()) return;
    setSaving(true);
    try {
      const payload = {
        companyId:     form.company_id!,
        auditTypeId:   form.auditTypeId,
        standardIds:   form.standardIds,
        validityPeriod: form.validityPeriod || "",
        auditMode:     form.auditMode || "Physical",
        currentStage:  form.currentStage || "Stage 1",
        remarks:       form.remarks || "",
        status:        form.status,
      };
      if (isEdit && editId) {
        await updateCompanyAudit(editId, payload as any);
        toast.success("Audit updated successfully");
      } else {
        const created = await createCompanyAudit(payload as any);
        // ✅ Immediately add new audit to dropdown opts so it appears before re-fetch
        const newAuditOpt = { value: created.id, label: `Audit #${created.id}` };
        setCompanyAuditOpts((prev) => {
          const exists = prev.some((o) => o.value === created.id);
          return exists ? prev : [...prev, newAuditOpt];
        });
        // ✅ Mirrors React: store as latestAudit and pre-fill stageName from currentStage
        setLatestAuditData(created);
        setCurrentAuditId(created.id);
        setStageForm((p) => ({
          ...p,
          auditId:   created.id,
          stageName: (created as any).currentStage || form.currentStage || "Stage 1",
        }));
        // Re-fetch audits list so Select Audit dropdown is updated
        if (form.company_id) await fetchCompanyAudits(form.company_id);
        toast.success("Audit scheduled! Now add stages below.");
        setActiveTab("auditStages");
      }
      refreshData?.();
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to save audit");
    } finally {
      setSaving(false);
    }
  };

  // ── Submit: Save Stage — same payload shape as React ──────────────────────
  const handleSaveStage = async (e?: React.FormEvent) => {
    e?.preventDefault();
    const targetAuditId = stageForm.auditId ?? currentAuditId;
    if (!targetAuditId) {
      toast.error("Please select or schedule an audit first");
      setActiveTab("scheduleAudit");
      return;
    }
    if (!stageForm.auditDate) { toast.error("Audit date is required"); return; }
    setSavingStage(true);
    try {
      await fetchApi<any>(`${AUDIT_STAGES_API_BASE_URL}/company-audit-stages`, {
        method: "POST",
        body: JSON.stringify({
          auditId:         targetAuditId,
          stageName:       stageForm.stageName,
          auditDate:       stageForm.auditDate,
          auditById:       stageForm.auditById || null,
          technicalExpert: stageForm.technicalExpert || "",
          anzicCode:       stageForm.anzicCode || "",
          remarks:         stageForm.remarks || "",
          createdById:     1,
        }),
      });
      // Also update the audit's currentStage
      await updateCompanyAudit(targetAuditId, { currentStage: stageForm.stageName } as any);
      toast.success("Stage saved successfully!");
      // ✅ Re-fetch audits to reflect latest record (updates latestAuditData + dropdown)
      if (form.company_id) {
        await fetchCompanyAudits(form.company_id);
      }
      setStageForm((p) => ({ ...p, auditDate: "", remarks: "", technicalExpert: "", anzicCode: "" }));
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to save stage");
    } finally {
      setSavingStage(false);
    }
  };

  if (!isOpen) return null;

  // ── Derived select values ─────────────────────────────────────────────────
  const selCompany: SelectOption | null = companyInfo
    ? {
        value: companyInfo.id,
        label: companyInfo.name
          ? `${companyInfo.name}${companyInfo.company_code ? ` (${companyInfo.company_code})` : ""}`
          : String(companyInfo.id),
      }
    : preselectedCompanyId && preselectedCompanyName
      ? { value: preselectedCompanyId, label: preselectedCompanyName }
      : null;

  const selAuditType    = auditTypeOpts.find((t) => t.value === form.auditTypeId)      ?? null;
  const selStandards    = standardOpts.filter((s) => form.standardIds.includes(Number(s.value)));
  const selAuditMode    = AUDIT_MODE_OPTIONS.find((m) => m.value === form.auditMode)   ?? AUDIT_MODE_OPTIONS[0];
  const selStatus       = AUDIT_STATUS_OPTIONS.find((s) => s.value === form.status)    ?? AUDIT_STATUS_OPTIONS[0];
  const selStageAudit   = companyAuditOpts.find((a) => a.value === stageForm.auditId) ?? null;
  const selStageAuditor = auditorOpts.find((a) => a.value === stageForm.auditById)    ?? null;

  const TABS: { key: FormTab; label: string }[] = [
    { key: "companyInfo",   label: "Company Info"   },
    { key: "scheduleAudit", label: "Schedule Audit" },
    { key: "auditStages",   label: "Audit Stages"   },
  ];

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>

        {/* ── Header ── */}
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>
              🗂 {isEdit ? "Edit Audit" : "Audit Management"}
            </h2>
            <p className={styles.modalSubtitle}>
              {selCompany ? selCompany.label : isEdit ? "Edit audit record" : "Schedule a new audit"}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">✕</button>
        </div>

        {/* ── Tab bar ── */}
        <div style={{ display: "flex", background: "#f9fafb", borderBottom: "1px solid #e5e7eb" }}>
          {TABS.map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              type="button"
              style={{
                flex: 1, padding: "14px 8px",
                fontWeight: activeTab === tab.key ? 700 : 500,
                fontSize: 14, border: "none", background: "none", cursor: "pointer",
                borderBottom: activeTab === tab.key ? "2px solid #7c3aed" : "2px solid transparent",
                color: activeTab === tab.key ? "#6d28d9" : "#9ca3af",
                transition: "all 0.15s", marginBottom: -1,
              }}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* ── Loading ── */}
        {loadingEdit ? (
          <div className={styles.loadingSpinner}>
            <div className={styles.loadingSpinnerIcon} />Loading audit data...
          </div>
        ) : (
          <>
            <div className={styles.formBody}>

              {/* ══════════════════════════════════════════════════════════
                  TAB 1 — COMPANY INFO
              ══════════════════════════════════════════════════════════ */}
              {activeTab === "companyInfo" && (
                <div>
                  <div className={styles.sectionHeader}>
                    <span className={styles.sectionDot} />Company Selection
                  </div>

                  <div className={styles.formGroup}>
                    <label className={styles.label}>
                      Select Company <span style={{ color: "#ef4444" }}>*</span>
                    </label>
                    {/* AsyncSelect — 30 per request, debounced 350ms, never loads all 10k */}
                    <AsyncSelect
                      classNamePrefix="rselect"
                      loadOptions={loadCompanyOptions}
                      defaultOptions
                      cacheOptions
                      value={selCompany}
                      onChange={(s) => {
                        const cid = s ? Number(s.value) : undefined;
                        setForm((p) => ({ ...p, company_id: cid }));
                        setCompanyAuditOpts([]);
                        setStageForm((p) => ({ ...p, auditId: undefined }));
                        if (cid) { fetchCompanyInfo(cid); fetchCompanyAudits(cid); }
                        else { setCompanyInfo(null); }
                      }}
                      isClearable
                      isSearchable
                      placeholder="Type to search all companies..."
                      loadingMessage={() => "Searching..."}
                      noOptionsMessage={({ inputValue }) =>
                        inputValue ? "No companies found" : "Type to search..."
                      }
                    />
                    {errors.company_id && (
                      <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.company_id}</span>
                    )}
                  </div>

                  {companyLoading && (
                    <p style={{ color: "#9ca3af", textAlign: "center", padding: "16px 0" }}>
                      Loading company details...
                    </p>
                  )}

                  {companyInfo && !companyLoading && (
                    <div style={{ border: "1px solid #e5e7eb", borderRadius: 12, padding: 20, background: "#fff" }}>
                      <h3 style={{ margin: "0 0 16px", color: "#6d28d9", display: "flex", alignItems: "center", gap: 8, fontSize: 15, fontWeight: 700 }}>
                        🏢 Company Information
                      </h3>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                        {[
                          ["Code",    companyInfo.company_code || "—"],
                          ["Name",    companyInfo.name         || "—"],
                          ["Address", companyInfo.address      || "—"],
                          ["City",    companyInfo.city         || "—"],
                          ["Country", companyInfo.country?.name || String(companyInfo.country_id ?? "—")],
                          ["Contact", companyInfo.contact_person || "—"],
                          ["Email",   companyInfo.email        || "—"],
                        ].map(([label, value]) => (
                          <div
                            key={label}
                            style={{ border: "1px solid #e5e7eb", borderRadius: 8, padding: "10px 14px", background: "#fafafa" }}
                          >
                            <strong style={{ color: "#7c3aed", fontSize: 12, display: "block", marginBottom: 2 }}>{label}:</strong>
                            <span style={{ color: "#111827", fontSize: 14 }}>{value}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {!companyInfo && !companyLoading && (
                    <div style={{ textAlign: "center", padding: "40px 0", color: "#9ca3af" }}>
                      <div style={{ fontSize: 36, marginBottom: 8 }}>🏢</div>
                      Search and select a company above to see its details
                    </div>
                  )}
                </div>
              )}

              {/* ══════════════════════════════════════════════════════════
                  TAB 2 — SCHEDULE AUDIT
                  Fields match React screenshot exactly:
                  Audit Type | Standard (multi)
                  Validity Period | Audit Mode
                  Current Stage | Status
                  Remarks (full width)
              ══════════════════════════════════════════════════════════ */}
              {activeTab === "scheduleAudit" && (
                <div>
                  <div className={styles.sectionHeader}>
                    <span className={styles.sectionDot} />Schedule Audit
                  </div>
                  <div className={styles.grid2}>

                    {/* Audit Type */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Audit Type</label>
                      <Select
                        classNamePrefix="rselect"
                        options={auditTypeOpts}
                        value={selAuditType}
                        onChange={(s) => setForm((p) => ({ ...p, auditTypeId: s ? Number(s.value) : undefined }))}
                        isLoading={dropdownsLoading}
                        placeholder="Select Audit Type"
                      />
                      {errors.auditTypeId && (
                        <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.auditTypeId}</span>
                      )}
                    </div>

                    {/* Standard (multi-select) */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Standard</label>
                      <Select
                        classNamePrefix="rselect"
                        isMulti
                        options={standardOpts}
                        value={selStandards}
                        onChange={(selected) =>
                          setForm((p) => ({ ...p, standardIds: (selected as SelectOption[]).map((s) => Number(s.value)) }))
                        }
                        isLoading={dropdownsLoading}
                        isSearchable
                        placeholder="Select Standards"
                        closeMenuOnSelect={false}
                      />
                      {errors.standardIds && (
                        <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.standardIds}</span>
                      )}
                    </div>

                    {/* Validity Period */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Validity Period</label>
                      <input
                        type="text"
                        value={form.validityPeriod}
                        onChange={(e) => setForm((p) => ({ ...p, validityPeriod: e.target.value }))}
                        className={styles.input}
                        placeholder="e.g. 2025-2026"
                      />
                    </div>

                    {/* Audit Mode */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Audit Mode</label>
                      <select
                        value={form.auditMode}
                        onChange={(e) => setForm((p) => ({ ...p, auditMode: e.target.value }))}
                        className={styles.input}
                      >
                        <option value="Physical">Physical</option>
                        <option value="Online">Online</option>
                        <option value="Hybrid">Hybrid</option>
                      </select>
                    </div>

                    {/* Current Stage */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Current Stage</label>
                      <select
                        value={form.currentStage}
                        onChange={(e) => setForm((p) => ({ ...p, currentStage: e.target.value }))}
                        className={styles.input}
                      >
                        {STAGE_NAMES.map((s) => <option key={s} value={s}>{s}</option>)}
                      </select>
                    </div>

                    {/* Status */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Status</label>
                      <select
                        value={form.status}
                        onChange={(e) => setForm((p) => ({ ...p, status: e.target.value }))}
                        className={styles.input}
                      >
                        <option value="Scheduled">Scheduled</option>
                        <option value="Ongoing">Ongoing</option>
                        <option value="Completed">Completed</option>
                        <option value="Cancelled">Cancelled</option>
                      </select>
                    </div>

                    {/* Remarks (full width) */}
                    <div className={`${styles.formGroup} ${styles.full}`}>
                      <label className={styles.label}>Remarks</label>
                      <textarea
                        value={form.remarks}
                        onChange={(e) => setForm((p) => ({ ...p, remarks: e.target.value }))}
                        className={styles.textarea}
                        rows={3}
                        placeholder="Add remarks..."
                      />
                    </div>
                  </div>
                </div>
              )}

              {/* ══════════════════════════════════════════════════════════
                  TAB 3 — AUDIT STAGES
                  Fields match React screenshot exactly:
                  Select Audit | Stage Name
                  Audit Date   | Audit By
                  Technical Expert | ANZIC Code
                  Remarks (full width)
              ══════════════════════════════════════════════════════════ */}
              {activeTab === "auditStages" && (
                <div>
                  {/* Warn if no audit available */}
                  {companyAuditOpts.length === 0 && !currentAuditId && (
                    <div style={{ background: "#fffbeb", border: "1px solid #fcd34d", borderRadius: 10, padding: "14px 18px", marginBottom: 20, display: "flex", gap: 10, alignItems: "center" }}>
                      <span style={{ fontSize: 20 }}>⚠️</span>
                      <div>
                        <strong style={{ color: "#92400e" }}>No audit scheduled yet.</strong>
                        <p style={{ margin: "4px 0 0", color: "#92400e", fontSize: 13 }}>
                          Please complete the Schedule Audit tab first.
                        </p>
                      </div>
                      <button
                        onClick={() => setActiveTab("scheduleAudit")}
                        style={{ marginLeft: "auto", padding: "8px 16px", background: "#f59e0b", color: "#fff", border: "none", borderRadius: 8, fontWeight: 600, cursor: "pointer", fontSize: 13 }}
                      >
                        Go to Schedule Audit
                      </button>
                    </div>
                  )}

                  {/* Stage history timeline */}
                  {/* Add Audit Stage form */}
                  <div className={styles.sectionHeader}>
                    <span className={styles.sectionDot} />Add Audit Stage
                  </div>
                  <div className={styles.grid2}>

                    {/* Select Audit — matches React screenshot */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Select Audit</label>
                      <Select
                        classNamePrefix="rselect"
                        options={companyAuditOpts}
                        value={selStageAudit}
                        onChange={(s) => {
                          const aid = s ? Number(s.value) : undefined;
                          setStageForm((p) => ({ ...p, auditId: aid }));
                          if (aid) { setCurrentAuditId(aid); }
                        }}
                        placeholder="Select..."
                        noOptionsMessage={() =>
                          form.company_id
                            ? "No audits found for this company"
                            : "Select a company first"
                        }
                      />
                    </div>

                    {/* Stage Name */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Stage Name</label>
                      <select
                        value={stageForm.stageName}
                        onChange={(e) => setStageForm((p) => ({ ...p, stageName: e.target.value }))}
                        className={styles.input}
                      >
                        {STAGE_NAMES.map((s) => <option key={s} value={s}>{s}</option>)}
                      </select>
                    </div>

                    {/* Audit Date */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Audit Date</label>
                      <input
                        type="date"
                        value={stageForm.auditDate}
                        onChange={(e) => setStageForm((p) => ({ ...p, auditDate: e.target.value }))}
                        className={styles.input}
                      />
                    </div>

                    {/* Audit By */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Audit By</label>
                      <Select
                        classNamePrefix="rselect"
                        options={auditorOpts}
                        value={selStageAuditor}
                        onChange={(s) => setStageForm((p) => ({ ...p, auditById: s ? Number(s.value) : undefined }))}
                        isSearchable
                        placeholder="Select..."
                      />
                    </div>

                    {/* Technical Expert */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>Technical Expert</label>
                      <input
                        type="text"
                        value={stageForm.technicalExpert}
                        onChange={(e) => setStageForm((p) => ({ ...p, technicalExpert: e.target.value }))}
                        className={styles.input}
                        placeholder="Expert name..."
                      />
                    </div>

                    {/* ANZIC Code */}
                    <div className={styles.formGroup}>
                      <label className={styles.label}>ANZIC Code</label>
                      <input
                        type="text"
                        value={stageForm.anzicCode}
                        onChange={(e) => setStageForm((p) => ({ ...p, anzicCode: e.target.value }))}
                        className={styles.input}
                        placeholder="e.g. 1234"
                      />
                    </div>

                    {/* Remarks (full width) */}
                    <div className={`${styles.formGroup} ${styles.full}`}>
                      <label className={styles.label}>Remarks</label>
                      <textarea
                        value={stageForm.remarks}
                        onChange={(e) => setStageForm((p) => ({ ...p, remarks: e.target.value }))}
                        className={styles.textarea}
                        rows={3}
                        placeholder="Add remarks..."
                      />
                    </div>
                  </div>
                </div>
              )}

            </div>{/* /formBody */}

            {/* ── Footer — same CSS classes as CompanyForm ── */}
            <div className={styles.modalFooter}>
              {activeTab === "companyInfo" && (
                <>
                  <button type="button" onClick={onClose} className={styles.cancelBtn}>Cancel</button>
                  <button
                    type="button"
                    onClick={() => setActiveTab("scheduleAudit")}
                    disabled={!form.company_id}
                    className={styles.saveBtn}
                  >
                    Next: Schedule Audit →
                  </button>
                </>
              )}
              {activeTab === "scheduleAudit" && (
                <>
                  <button type="button" onClick={() => setActiveTab("companyInfo")} className={styles.cancelBtn}>
                    ← Back
                  </button>
                  <button
                    type="button"
                    disabled={saving}
                    className={styles.saveBtn}
                    onClick={() => handleSubmitAudit()}
                  >
                    {saving
                      ? (isEdit ? "Updating..." : "Scheduling...")
                      : (isEdit ? "Update Audit" : "Schedule Audit")}
                  </button>
                </>
              )}
              {activeTab === "auditStages" && (
                <>
                  <button type="button" onClick={onClose} className={styles.cancelBtn}>Close</button>
                  <button
                    type="button"
                    disabled={savingStage || (!stageForm.auditId && !currentAuditId)}
                    className={styles.saveBtn}
                    onClick={() => handleSaveStage()}
                  >
                    {savingStage ? "Saving..." : "Save Stage"}
                  </button>
                </>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}