// Visit Plan — Company Context (Bucket C). Read-only reference tabs for the plan's company
// (Company Production / Product / Visit Report / SO / Quotation / LWR). Each tab's data is
// lazy-loaded once via useHttp (route visit-plans.context) as { cols, rows } and cached.
// Essential columns only (user decision 2026-07-17). Mirrors the Create page's Company Context
// look, but self-contained + read-only (no Action/Edit/History columns).
import { useEffect, useRef, useState } from 'react';
import { useHttp } from '@inertiajs/react';
import { BarChart3, Building2, ClipboardList, CreditCard, FileStack, Loader2, Factory, MapPin, Package, FileText, ReceiptText, ShoppingCart, ScrollText, FlaskConical, TrendingUp, Users } from 'lucide-react';

const TH = 'whitespace-nowrap bg-secondary/60 px-3 py-2 text-left text-[10.5px] font-semibold uppercase tracking-wide text-muted-foreground';
// Icons follow the Company Records block (Components/MenuCompanies/CompanyTabs.jsx) so the same
// pane wears the same glyph wherever it is embedded.
const ICONS = {
    address: MapPin, npwp: FileText, reference: Users, creditCeiling: CreditCard,
    production: Factory, product: Package, graph: BarChart3, visit: ClipboardList,
    visitAll: FileStack, so: ShoppingCart, quotation: ScrollText, lwr: FlaskConical,
    nsSj: ReceiptText, nsSjAnalysis: TrendingUp,
};
const isNum = (c) => /qty|price|volume|quantity/i.test(c);

// Subtle status pill tone from the status text (SO/Quotation/LWR/Visit statuses vary).
function toneOf(status) {
    const s = String(status || '').toLowerCase();
    if (/cancel|reject/.test(s)) return 'bg-danger/10 text-danger';
    if (/submit|approv|done|print|confirm|complete|receive/.test(s)) return 'bg-success/10 text-success';
    if (/revise|pending|feedback|request|process/.test(s)) return 'bg-warning/10 text-warning';
    return 'bg-secondary text-muted-foreground';
}

// `fromProject` (create-from-project only): the company-keyed endpoint sits behind
// assertCompanyPickable(), whose narrow exemption for a project's company only runs when the
// request carries ?fromProject=. Omitted everywhere else, so the URL is byte-identical there.
export default function CompanyContextTabs({ tabs = [], planId, companyId = undefined, fromProject = null }) {
    const http = useHttp({});
    // Two modes: REPORT (fixed planId) and CREATE (companyId, which changes as the user picks a
    // company — #106). `contextKey` is whichever id we fetch by; the cache is keyed by it so
    // switching the company invalidates cleanly.
    const isCompanyMode = companyId !== undefined;
    const contextKey = isCompanyMode ? companyId : planId;
    const [tab, setTab] = useState(tabs[0]?.key ?? '');
    const [cache, setCache] = useState({}); // `${contextKey}::${tabKey}` → { cols, rows }
    const [loading, setLoading] = useState(false);
    const reqSeq = useRef(0);
    const ck = (key) => `${contextKey}::${key}`;

    const load = async (key) => {
        if (!key || !contextKey) return;
        setTab(key);
        if (cache[ck(key)]) return; // already fetched for this company/plan
        const seq = ++reqSeq.current;
        setLoading(true);
        try {
            const url = isCompanyMode
                ? route('visit-plans.context-company', { company: contextKey, tab: key, ...(fromProject ? { fromProject } : {}) })
                : route('visit-plans.context', { visitPlan: contextKey, tab: key });
            const data = (await http.get(url)) ?? { cols: [], rows: [] };
            if (seq === reqSeq.current) setCache((c) => ({ ...c, [ck(key)]: data }));
        } finally {
            if (seq === reqSeq.current) setLoading(false);
        }
    };

    // Load the active tab on mount AND whenever the company/plan changes (create: a new company
    // → refetch). Tab clicks are handled by onClick → load(key).
    useEffect(() => {
        if (contextKey) load(tab || tabs[0]?.key);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [contextKey]);

    const data = cache[ck(tab)];

    return (
        <div className="p-5">
            <div className="-mx-1 mb-4 flex flex-wrap gap-1 overflow-x-auto border-b border-border/50 px-1">
                {tabs.map((t) => {
                    const on = t.key === tab;
                    const Icon = ICONS[t.key] ?? Building2;
                    return (
                        <button key={t.key} type="button" onClick={() => load(t.key)}
                            className={`-mb-px inline-flex items-center gap-1.5 whitespace-nowrap rounded-t-lg border-b-2 px-3 py-2 text-xs font-bold transition-colors ${on ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}>
                            <Icon className="size-3.5" /> {t.label}
                        </button>
                    );
                })}
            </div>

            {!contextKey ? (
                <p className="py-10 text-center text-sm text-muted-foreground">Pilih perusahaan dulu untuk melihat context.</p>
            ) : loading && !data ? (
                <div className="flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground">
                    <Loader2 className="size-4 animate-spin" /> Memuat…
                </div>
            ) : !data || data.rows.length === 0 ? (
                // `notice` comes from the NetSuite panes (CompanyNsPanelService). Its two states are
                // NOT interchangeable with the generic line below: "Customer Have No Synchronization
                // To Oracle" means the company was never linked, while "no data" means it was linked
                // and has nothing to show. Collapsing them tells the reader the opposite of the truth
                // in one of the two cases.
                <p className="py-10 text-center text-sm text-muted-foreground">
                    {data?.notice || 'Tidak ada data untuk perusahaan ini.'}
                </p>
            ) : (
                <div className="overflow-x-auto rounded-xl border border-border/70">
                    <table className="w-full border-collapse">
                        <thead>
                            <tr>
                                <th className={`${TH} w-10 text-center`}>#</th>
                                {data.cols.map((c) => <th key={c} className={`${TH} ${isNum(c) ? 'text-right' : ''}`}>{c}</th>)}
                            </tr>
                        </thead>
                        <tbody>
                            {data.rows.map((row, i) => (
                                <tr key={i} className="border-t border-border/60 align-top hover:bg-muted/20">
                                    <td className="whitespace-nowrap px-3 py-2 text-center text-[11px] font-bold tabular-nums text-muted-foreground">{i + 1}</td>
                                    {row.map((cell, j) => {
                                        const col = data.cols[j];
                                        if (col === 'Status') {
                                            return (
                                                <td key={j} className="whitespace-nowrap px-3 py-2">
                                                    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10.5px] font-bold ${toneOf(cell)}`}>{cell || '—'}</span>
                                                </td>
                                            );
                                        }
                                        const empty = cell === '' || cell == null;
                                        return (
                                            <td key={j} className={`whitespace-nowrap px-3 py-2 text-[11.5px] ${isNum(col) ? 'text-right tabular-nums' : ''} ${empty ? 'text-muted-foreground/60' : 'text-foreground'}`}>
                                                {empty ? '—' : cell}
                                            </td>
                                        );
                                    })}
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
}
