import { useState } from 'react';
import { Link } from '@inertiajs/react';
import { ArrowLeft, MapPin, Phone, Printer } from 'lucide-react';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import CompanyTabs from '@/Components/MenuCompanies/CompanyTabs';
import { StageActionPanel } from '@/Components/MenuCompanies/CustomerData/StageActionPanel';
import { stripHtml } from '@/Components/MenuCompanies/CustomerData/stripHtml';
import { CustomerArPending } from '@/Components/MenuQuotations/CustomerOutstanding/CustomerArPending';
import { PaymentAfterDueDate } from '@/Components/MenuCompanies/CustomerData/PaymentAfterDueDate';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import { useCustomerAr } from '@/Hooks/useCustomerAr';

export const fmt = (n) => Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
export const fmtId = (n) => Number(n || 0).toLocaleString('id-ID', { maximumFractionDigits: 0 });
// Legacy Payment Rating scale (0 = "Select Rating"): shown as its label, not the number.
const RATING_LABELS = { 1: 'Bad', 2: 'Not Good', 3: 'Good', 4: 'Very Good', 5: 'Excellent' };

// Doc-section grammar copied from the Quotation detail reference page.
export const DOC_SECTION = 'relative rounded-xl border border-border bg-card px-4 pt-3.5 pb-3 shadow-sm';
export const DOC_HEADING = 'm-0 mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground';
export const DOC_ICON = 'inline-grid size-6 shrink-0 place-items-center rounded-full border border-primary/50 bg-transparent text-primary';
export const BACK_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary';

// Read-only label:value rows with hairline dividers (QuotationDetailPage's DocList).
export function DocList({ fields }) {
    const entries = Object.entries(fields).filter(([, v]) => v !== undefined);
    if (!entries.length) return <p className="px-0 py-1 text-[0.82rem] text-muted-foreground">Tidak ada data.</p>;
    return (
        <dl className="grid gap-0">
            {entries.map(([key, val]) => {
                const isNil = val === null || val === undefined || val === '' || val === '—';
                return (
                    <div key={key} className="grid grid-cols-[minmax(0,130px)_1fr] items-baseline gap-2.5 border-b border-border/40 py-2 last:border-b-0">
                        <dt className="m-0 text-[11.5px] font-normal text-muted-foreground/80">{key}</dt>
                        <dd className={`m-0 wrap-break-word text-[12.5px] ${isNil ? 'font-normal text-muted-foreground/40' : 'font-medium text-foreground'}`}>
                            {isNil ? '—' : val}
                        </dd>
                    </div>
                );
            })}
        </dl>
    );
}

// Two-up label-over-value grid for short values (halves the card height vs rows).
// Keys listed in `wide` span the full width (long free text like Remark).
export function DocGrid({ fields, wide = [] }) {
    const entries = Object.entries(fields).filter(([, v]) => v !== undefined);
    if (!entries.length) return <p className="px-0 py-1 text-[0.82rem] text-muted-foreground">Tidak ada data.</p>;
    return (
        <dl className="grid grid-cols-2 gap-x-4 gap-y-3 pt-1">
            {entries.map(([key, val]) => {
                const isNil = val === null || val === undefined || val === '' || val === '—';
                return (
                    <div key={key} className={`min-w-0 ${wide.includes(key) ? 'col-span-2' : ''}`}>
                        <dt className="m-0 text-[11px] font-normal text-muted-foreground/80">{key}</dt>
                        <dd className={`m-0 mt-0.5 wrap-break-word text-[12.5px] ${isNil ? 'font-normal text-muted-foreground/40' : 'font-medium text-foreground'}`}>
                            {isNil ? '—' : val}
                        </dd>
                    </div>
                );
            })}
        </dl>
    );
}

export const SectionIcon = ({ children }) => <span className={DOC_ICON} aria-hidden="true">{children}</span>;

// Yes/No as a small pill — a visual anchor between the text rows.
export const YesNo = ({ value }) => (
    <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-bold ${value ? 'bg-success/10 text-success-text' : 'bg-secondary text-muted-foreground'}`}>
        <span aria-hidden="true" className="size-1.5 rounded-full bg-current" />{value ? 'Yes' : 'No'}
    </span>
);

/**
 * Shared detail + action scaffold for the approval stages — restyled 2026-07-17 to the
 * Quotation-detail grammar: hero + stats strip (key numbers + history clock popover) +
 * three DocList section cards, then the NetSuite AR panels and the sticky decision dock.
 * Per-stage flags mirror the legacy field set:
 *   - showPaymentRating: read-only Payment Rating (SM/CEO/AST). Finance edits it in the panel → false.
 *   - showApproved: read-only Approved CC/Term/TOP/AddTOP/Special Condition (AST only). CEO edits
 *     them in the panel; Finance/SM don't show them at all.
 *   - showPaymentAfterDueDate: the second NetSuite panel (Finance + SM).
 * `actionLabel` names the primary button; `initialData` + `renderFields(form)` add the editable inputs.
 */
export function StageDetailPage({
    title, backRoute, creditCeiling: cc, canAct, actionRoutes, actionLabel = 'Approve',
    initialData = {}, renderFields = null,
    showPaymentAfterDueDate = false, showPaymentRating = true, showApproved = false, creditGuard = false,
    showArTabs = true, showMetricTable = true,
    companyRecordsReadOnly = false,
    companyRecordsPreset = 'ccStage',
    children = null,
}) {
    

    // Customer Outstanding (AR) — legacy "Detail Invoice" shown on every CC approval stage.
    const customerAr = useCustomerAr(cc.companyId ?? null, 'customer-ar.pending.byCompany');
    // "Payment after Due" — legacy Finance + SM + CEO. Hook always runs (Rules of Hooks);
    // companyId=null when the stage doesn't want it → no fetch.
    const paymentDueDate = useCustomerAr(showPaymentAfterDueDate ? (cc.companyId ?? null) : null, 'customer-ar.payment-due-date.byCompany');

    // Legacy checkButton (SM/CEO): warn before Approve when AR breaches the credit limit,
    // is overdue, or is still outstanding. Null (no warning) until AR data loads or when unset.
    const arSummary = customerAr.data?.summary;
    const arRows = customerAr.data?.rows ?? [];
    const approveWarning = creditGuard && arSummary
        && (arSummary.overLimit || arSummary.totalBalance > 0 || arRows.some((r) => r.overdueDays > 0))
        ? 'AR Company telah melebihi Credit Limit atau sudah Jatuh Tempo!'
        : null;

    // History → the clock-popover timeline (Quotation grammar). Request rows carry the
    // proposed figures in the comment so no legacy data is lost.
    const historyEntries = (cc.history ?? []).map((h) => ({
        Status: h.status,
        Tanggal: h.tanggal,
        User: h.nama,
        Comment: [stripHtml(h.remark), h.statusId === 1 ? `Proposed CC ${fmtId(h.proposedCC)} · Proposed TOP ${fmtId(h.proposedTOP)}` : '']
            .filter(Boolean).join(' — '),
    }));

    const tabs = [
        { id: 'ar', label: 'Customer Outstanding' },
    ];
    if (showPaymentAfterDueDate) {
        tabs.push({ id: 'payment', label: 'Payment Behaviour' });
    }

    const [activeTab, setActiveTab] = useState('ar');

    return (
        <div className="space-y-4">
            {/* Hero */}
            <div className="flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                <div className="flex min-w-0 flex-col gap-1">
                    <div className="flex items-center gap-3">
                        <h1 className="m-0 text-2xl font-extrabold tracking-tight text-foreground">{title} #{cc.id}</h1>
                        <StatusBadge tone="neutral">{cc.status}</StatusBadge>
                    </div>
                </div>
                <div className="flex items-center gap-2 self-end sm:self-auto">
                    {historyEntries.length > 0 && (
                        <HistoryTimelinePopover entries={historyEntries} />
                    )}
                    <Link href={route(backRoute)} className={BACK_BTN}>
                        <ArrowLeft className="size-3.5" />Back to List
                    </Link>
                </div>
            </div>

            <div className="pt-2">
                <section className={DOC_SECTION}>
                    {/* Header banner — grouped by WHAT the values are, not by where they fit.
                        Until 2026-08-24 all four of AST Code, NetSuite ID, phone and fax sat in
                        one "metadata strip" under the address: a 1222px-wide row whose content
                        stopped around a third of the way across, leaving most of the banner's
                        right side empty while the left stacked four rows deep.
                        Now: LEFT is the company and how to reach it (phone and fax join the
                        address — they are all contact data), RIGHT is the pair of external
                        system keys. */}
                    <div className="pb-3.5 mb-4 border-b border-border/40">
                        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-6">
                            {/* Left: identity + contact */}
                            <div className="min-w-0 space-y-1">
                                <div className="flex flex-wrap items-center gap-2">
                                    <h2 className="m-0 text-[15px] font-bold tracking-tight text-foreground">{cc.company}</h2>
                                    <span className="text-[13px] font-semibold text-muted-foreground/60 tabular-nums">#{cc.companyId}</span>
                                </div>

                                {(cc.division || cc.industry) && (
                                    <p className="m-0 text-[11.5px] font-medium text-muted-foreground">
                                        {[cc.division, cc.industry].filter(Boolean).join(' • ')}
                                    </p>
                                )}

                                <div className="flex flex-wrap items-center gap-x-4 gap-y-1 pt-0.5 text-[11.5px]">
                                    {cc.companyAddress && (
                                        <span className="flex min-w-0 items-center gap-1 font-normal text-muted-foreground/80">
                                            <MapPin aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground/70" /> {cc.companyAddress}{cc.zipCode ? ` · ${cc.zipCode}` : ''}
                                        </span>
                                    )}
                                    {cc.companyTelephone && (
                                        <span className="flex items-center gap-1.5">
                                            <Phone aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
                                            <span className="font-medium text-foreground">{cc.companyTelephone}</span>
                                        </span>
                                    )}
                                    {cc.companyFax && (
                                        <span className="flex items-center gap-1.5">
                                            <Printer aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
                                            <span className="font-medium text-foreground">{cc.companyFax}</span>
                                        </span>
                                    )}
                                </div>
                            </div>

                            {/* Right: the two external system keys. A 2-column grid rather than
                                inline label:value pairs so both monospace values start on the
                                same x — the point of a right-hand key block is that the codes
                                line up and can be compared at a glance. No justify-items-end:
                                that aligns their RIGHT edges, which for unequal-length codes
                                leaves the first characters ragged (measured 1496 vs 1503).
                                shrink-0 keeps a long address from squeezing them. */}
                            <dl className="grid shrink-0 grid-cols-[auto_auto] items-baseline gap-x-3 gap-y-1 text-[11.5px]">
                                <dt className="m-0 font-normal text-muted-foreground">AST Code</dt>
                                <dd className="m-0 font-mono font-semibold text-foreground">{cc.astCompanyCode || '—'}</dd>
                                <dt className="m-0 font-normal text-muted-foreground">NetSuite ID</dt>
                                <dd className="m-0 font-mono font-semibold text-foreground">{cc.nsCustomerId || '—'}</dd>
                            </dl>
                        </div>
                    </div>

                    {/* Main Content Layout — REQUEST & DETAILS beside a two-up COMMERCIAL PROFILE.
                        Every credit-ceiling detail route merges companyProfile() onto its payload,
                        so this is the only layout. The old lean-payload fallback (one narrow column
                        that left the right two-thirds of the card blank, and Yes/No pills reading
                        `undefined` as "No") is gone with the lean payloads it was written for. */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-x-8 gap-y-6">
                        {/* Column 1: REQUEST & DETAILS */}
                        <div>
                            <h3 className="m-0 mb-3 text-[11px] font-extrabold uppercase tracking-wider text-muted-foreground/80">
                                REQUEST &amp; DETAILS
                            </h3>
                            <DocList fields={{
                                'Branch': cc.branch,
                                'Sales': cc.sales,
                                'Request Creator': cc.creator,
                                'Justification': cc.justification,
                                'Remark Creator': stripHtml(cc.remark),
                            }} />
                        </div>

                        {/* Columns 2 & 3: COMMERCIAL PROFILE (2 Sub-Columns) */}
                        <div className="md:col-span-2 md:pl-8 md:border-l md:border-border/40">
                            <h3 className="m-0 mb-3 text-[11px] font-extrabold uppercase tracking-wider text-muted-foreground/80">
                                COMMERCIAL PROFILE
                            </h3>
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8">
                                <DocList fields={{
                                    'Multinational': <YesNo value={cc.isMultinational} />,
                                    'Customer Since': cc.customerSince,
                                    'Company Owners': cc.companyOwner,
                                    'Office Premises': cc.officePremises,
                                    'Highest Value': cc.highestValueAchieved,
                                }} />
                                <DocList fields={{
                                    'Established': cc.customerEst,
                                    'Order with PO': <YesNo value={cc.orderWithPO} />,
                                    'Company Group': cc.companyGroup,
                                    'Factory Premises': cc.factoryPremises,
                                    'Company Remark': cc.companyRemark,
                                }} />
                            </div>
                        </div>
                    </div>

                    {showApproved && (
                        <div className="mt-4 pt-3 border-t border-border/30">
                            <h4 className="m-0 mb-2 text-[11px] font-bold uppercase tracking-wider text-success-text">Approval Details</h4>
                            <DocList fields={{
                                'Approved CC': cc.approvedCC ? fmt(cc.approvedCC) : '—',
                                'Approved Term': cc.approvedTerm,
                                'Approved TOP': cc.approvedTOP,
                                'Approved Add. TOP': cc.approvedAdditionalTOP,
                                'Special Condition': cc.specialCondition,
                            }} />
                        </div>
                    )}
                </section>
            </div>

            {/* Tabs Header & Content */}
            {showArTabs && (
                <>
                    <div className="flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-border mt-4">
                        {tabs.map((t) => (
                            <button
                                key={t.id}
                                type="button"
                                onClick={() => setActiveTab(t.id)}
                                className={`relative pb-3 text-[13px] font-bold transition-colors ${activeTab === t.id ? 'text-primary' : 'text-muted-foreground hover:text-foreground'}`}
                            >
                                {t.label}
                                {activeTab === t.id && (
                                    <span className="absolute bottom-0 left-0 w-full h-[2px] bg-primary rounded-t-full" />
                                )}
                            </button>
                        ))}
                    </div>

                    <div className="pt-2 pb-4">
                        {activeTab === 'ar' && (
                            <CustomerArPending data={customerAr.data} loading={customerAr.loading} />
                        )}
                        {activeTab === 'payment' && showPaymentAfterDueDate && (
                            <PaymentAfterDueDate data={paymentDueDate.data} loading={paymentDueDate.loading} />
                        )}
                    </div>
                </>
            )}

            {/* Before - Propose - Approved Table */}
            {showMetricTable && (
                <div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden mb-6">
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-[12.5px] whitespace-nowrap bg-card">
                            <thead className="bg-transparent text-muted-foreground border-b border-border/60">
                                <tr>
                                    <th className="px-4 py-3 font-bold uppercase tracking-wider text-[11px] w-1/4">Metric</th>
                                    <th className="px-4 py-3 font-bold uppercase tracking-wider text-[11px] w-1/4">Before</th>
                                    <th className="px-4 py-3 font-bold uppercase tracking-wider text-[11px] w-1/4 text-primary">Proposed</th>
                                    <th className="px-4 py-3 font-bold uppercase tracking-wider text-[11px] w-1/4 text-success-text">Approved</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border/40">
                                <tr>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">Credit Ceiling (IDR)</td>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">—</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{fmt(cc.proposedCC)}</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{cc.approvedCC !== null && cc.approvedCC !== undefined ? fmt(cc.approvedCC) : '—'}</td>
                                </tr>
                                <tr>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">Payment Term</td>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">—</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{cc.proposedTerm || '—'}</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{cc.approvedTerm || '—'}</td>
                                </tr>
                                <tr>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">TOP (Days)</td>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">—</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{cc.proposedTOP ?? '—'}</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{cc.approvedTOP ?? '—'}</td>
                                </tr>
                                <tr>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">Additional TOP</td>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">—</td>
                                    <td className="px-4 py-3 font-bold text-foreground">—</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{cc.approvedAdditionalTOP ?? '—'}</td>
                                </tr>
                                {showPaymentRating && (
                                    <tr>
                                        <td className="px-4 py-3 font-medium text-muted-foreground">Payment Rating</td>
                                        <td className="px-4 py-3 font-medium text-muted-foreground">—</td>
                                        <td className="px-4 py-3 font-bold text-foreground">{RATING_LABELS[cc.paymentRating] ?? (cc.paymentRating || '—')}</td>
                                        <td className="px-4 py-3 font-bold text-foreground">—</td>
                                    </tr>
                                )}
                                <tr>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">Revision Ver</td>
                                    <td className="px-4 py-3 font-medium text-muted-foreground">—</td>
                                    <td className="px-4 py-3 font-bold text-foreground">{cc.flagRevision ? cc.flagRevision : 'New'}</td>
                                    <td className="px-4 py-3 font-bold text-foreground">—</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {cc.companyId > 0 && (
                <CompanyTabs companyId={cc.companyId} preset={companyRecordsPreset} readOnly={companyRecordsReadOnly} />
            )}
            {/* ⚠️ `children` renders LAST on purpose. Its only caller passes a <DecisionBar>, and
                DecisionBar puts an in-flow 112px spacer next to its `fixed` pill to reserve the
                clearance the pill would otherwise hover over. Rendered above Company Records —
                where this used to sit — that spacer became a 112px hole in the middle of the page
                (measured 152px of dead space between the hero and Company Records) while the
                clearance it was meant to provide sat in the wrong place entirely. */}
            {children}
            <StageActionPanel routes={actionRoutes} canAct={canAct}
                approveLabel={actionLabel} initialData={initialData} renderFields={renderFields}
                approveWarning={approveWarning}
                summary={<><strong className="font-semibold text-foreground">#{cc.id}</strong> · {cc.company} · {cc.status}</>} />
        </div>
    );
}
