import { useForm, Link } from '@inertiajs/react';
import { ArrowLeft, Loader2, Send, Printer, Download } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { Button } from '@/Components/ui/button';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { useToast } from '@/Components/Toast';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import {
    fmt, fmtId, DOC_SECTION, DOC_HEADING, BACK_BTN,
    DocList, DocGrid, SectionIcon, YesNo,
} from '@/Components/MenuCompanies/CustomerData/StageDetailPage';
import { stripHtml } from '@/Components/MenuCompanies/CustomerData/stripHtml';
import CompanyTabs from '@/Components/MenuCompanies/CompanyTabs';
import { useNumberFormat } from '@/Hooks/useNumberFormat';
import { NativeSelect } from '@/Components/ui/native-select';
import { useCreditCeilingPdf } from '@/lib/pdf/useCreditCeilingPdf';

const PRIMARY_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4.5 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 disabled:opacity-60';
const inp = 'h-9 w-full rounded-md border border-input bg-card px-2 text-sm outline-none transition-colors focus:border-primary';

// Creator revise of a returned (status 6) request — faithful port of legacy creditceilingrevise.php,
// restyled 2026-07-27 to the CC stage-detail grammar (hero + stats strip + history clock + doc
// cards; the editable btn-recreate fields live in their own "Revise Details" form card).
// Editable: Proposed CC, Proposed Payment Terms, Proposed TOP (auto from term), Justification.
// Resubmits as Request (status 1).
export default function Revise({ creditCeiling: cc, options }) {
    const { show: showToast } = useToast();
    const ccPdf = useCreditCeilingPdf(cc.id);
    const form = useForm({
        ProposedCC: cc.proposedCC || '',
        ProposedTOP: cc.proposedTOP || '',
        // Pre-select the stored Justification / Payment Term (legacy pre-selects them).
        JustificationID: cc.justificationId ? String(cc.justificationId) : '',
        QuotationPaymentTermID: cc.paymentTermId ? String(cc.paymentTermId) : '',
    });

    // Live currency formatting for Proposed CC (legacy FormatCurrency + isNumber). Form state
    // keeps the RAW numeric string; the hook renders grouped separators and strips on input.
    const proposedCcFmt = useNumberFormat({
        value: form.data.ProposedCC,
        onChange: (raw) => form.setData('ProposedCC', raw),
        decimals: 2,
    });

    // Legacy gettop.php: choosing a Payment Term auto-fills Proposed TOP from the term's TermDay.
    const onPaymentTermChange = (e) => {
        const val = e.target.value;
        const term = (options?.paymentTerms ?? []).find((t) => String(t.id) === val);
        form.setData((d) => ({ ...d, QuotationPaymentTermID: val, ProposedTOP: term ? String(term.top) : '' }));
    };

    const submit = (e) => {
        e.preventDefault();
        form.post(route('credit-ceilings.revise.submit', cc.id), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    // History → the clock-popover timeline (Quotation grammar); Request rows keep the proposed figures.
    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 selectedTerm = (options?.paymentTerms ?? []).find((t) => String(t.id) === form.data.QuotationPaymentTermID);
    const stats = [
        { label: 'Proposed Credit Ceiling (IDR)', value: fmt(cc.proposedCC) },
        { label: 'Payment Term', value: selectedTerm?.name || '—' },
        { label: 'Proposed TOP', value: cc.proposedTOP ?? '—' },
        { label: 'Revision Ver', value: cc.flagRevision ? cc.flagRevision : 'New' },
    ];

    const companyFields = {
        'Branch': cc.branch,
        'Division': cc.division,
        'Industry': cc.industry,
        'Sales': cc.sales,
        'Telephone': cc.companyTelephone,
        'Fax': cc.companyFax,
    };
    const profileFields = {
        'Multinational': <YesNo value={cc.isMultinational} />,
        'Established': cc.customerEst,
        'Customer Since': cc.customerSince,
        'Company Owners': cc.companyOwner,
        'Company Group': cc.companyGroup,
        'Office Premises': cc.officePremises,
        'Factory Premises': cc.factoryPremises,
        'Order With PO': <YesNo value={cc.orderWithPO} />,
        'Highest Value': cc.highestValueAchieved,
        'AST Code': cc.astCompanyCode,
        'NetSuite ID': cc.nsCustomerId,
    };
    const ccFields = {
        'ID': cc.id,
        'Creator': cc.creator,
        'Remark Creator': stripHtml(cc.remark),
        'Approved CC (IDR)': fmt(cc.approvedCC),
        'Approved Term': cc.approvedTerm,
        'Approved TOP': cc.approvedTOP,
        'Approved Add. TOP': cc.approvedAdditionalTOP,
        'Special Condition': cc.specialCondition,
    };

    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">Revise · Credit Ceiling #{cc.id}</h1>
                        <StatusBadge tone="warning">{cc.status}</StatusBadge>
                    </div>
                    <p className="m-0 text-[13px] font-medium text-muted-foreground">{cc.company}</p>
                </div>
                <Link href={route('credit-ceilings.view-request')} className={BACK_BTN}>
                    <ArrowLeft className="size-3.5" />Back to List
                </Link>
            </div>

            {/* Stats strip — key figures + the history clock (Quotation grammar) */}
            <article className="flex flex-col gap-3 rounded-2xl border border-border bg-card p-[14px_18px] shadow-sm sm:flex-row sm:items-start">
                <div className="grid min-w-0 gap-x-4 gap-y-3 [grid-template-columns:repeat(2,minmax(0,1fr))] sm:flex-1 sm:gap-x-5 sm:[grid-template-columns:repeat(auto-fit,minmax(150px,1fr))]">
                    {stats.map((c) => (
                        <div key={c.label} className="flex min-w-0 flex-col gap-0.5">
                            <small className="block text-[11px] font-medium text-muted-foreground">{c.label}</small>
                            <strong className="block truncate text-[15px] font-extrabold leading-[1.1] text-card-foreground" title={String(c.value ?? '')}>{c.value}</strong>
                        </div>
                    ))}
                    {historyEntries.length > 0 && (
                        <div className="flex items-center sm:hidden">
                            <HistoryTimelinePopover entries={historyEntries} />
                        </div>
                    )}
                </div>
                {historyEntries.length > 0 && (
                    <div className="hidden shrink-0 self-stretch border-l border-border pl-3 sm:block">
                        <HistoryTimelinePopover entries={historyEntries} />
                    </div>
                )}
            </article>

            {/* Doc sections — same 3-up cards as the approval stages */}
            <div className="grid grid-cols-3 gap-3.5 max-[1180px]:grid-cols-2 max-[860px]:grid-cols-1">
                <section className={DOC_SECTION}>
                    <h3 className={DOC_HEADING}>
                        <SectionIcon>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M3 21h18" /><path d="M5 21V7l8-4v18" /><path d="M19 21V11l-6-4" />
                            </svg>
                        </SectionIcon>
                        Company &amp; Contact
                    </h3>
                    <div className="mb-1 border-b border-border/40 pb-2.5">
                        <div className="flex items-center justify-between gap-2">
                            <span className="truncate text-[13px] font-bold text-foreground" title={cc.company || ''}>{cc.company}</span>
                            <span className="shrink-0 rounded-full bg-secondary px-2 py-0.5 text-[10px] font-bold tabular-nums text-muted-foreground">#{cc.companyId}</span>
                        </div>
                        <p className="m-0 mt-1 text-[11.5px] leading-relaxed text-muted-foreground">{cc.companyAddress}{cc.zipCode ? ` · ${cc.zipCode}` : ''}</p>
                    </div>
                    <DocList fields={companyFields} />
                </section>

                <section className={DOC_SECTION}>
                    <h3 className={DOC_HEADING}>
                        <SectionIcon>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" />
                            </svg>
                        </SectionIcon>
                        Commercial Profile
                    </h3>
                    <DocGrid fields={profileFields} wide={['Highest Value']} />
                    {cc.companyRemark ? (
                        <div className="mt-3 border-t border-border/40 pt-2.5">
                            <p className="m-0 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground">Remark</p>
                            <p className="m-0 mt-0.5 text-[12px] leading-relaxed text-foreground/80">{cc.companyRemark}</p>
                        </div>
                    ) : null}
                </section>

                <section className={DOC_SECTION}>
                    <h3 className={DOC_HEADING}>
                        <SectionIcon>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <rect x="2" y="5" width="20" height="14" rx="2" /><line x1="2" y1="10" x2="22" y2="10" />
                            </svg>
                        </SectionIcon>
                        Credit Ceiling Info
                    </h3>
                    <DocList fields={ccFields} />
                </section>
            </div>

            {/* Revise Details — the editable btn-recreate fields, actions bottom-right */}
            <section className={DOC_SECTION}>
                <h3 className={DOC_HEADING}>
                    <SectionIcon>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
                        </svg>
                    </SectionIcon>
                    Revise Details
                </h3>
                <form onSubmit={submit} className="space-y-4 pb-1.5">
                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <div>
                            <label className="mb-1 block text-xs font-semibold text-muted-foreground">Proposed Credit Ceiling (IDR)</label>
                            <input type="text" {...proposedCcFmt} className={inp} placeholder="0.00" />
                            {form.errors.ProposedCC && <p className="mt-1 text-[11px] text-danger-text">{form.errors.ProposedCC}</p>}
                        </div>
                        <div>
                            <label className="mb-1 block text-xs font-semibold text-muted-foreground">Proposed Payment Terms</label>
                            <NativeSelect value={form.data.QuotationPaymentTermID}
                                onChange={onPaymentTermChange} className={inp}>
                                <option value="">Select Payment Term</option>
                                {(options?.paymentTerms ?? []).map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
                            </NativeSelect>
                            {form.errors.QuotationPaymentTermID && <p className="mt-1 text-[11px] text-danger-text">{form.errors.QuotationPaymentTermID}</p>}
                        </div>
                        <div>
                            <label className="mb-1 block text-xs font-semibold text-muted-foreground">Proposed TOP</label>
                            <input type="number" min="0" value={form.data.ProposedTOP} readOnly
                                className={`${inp} bg-muted text-muted-foreground`} />
                            <p className="mt-1 text-[11px] text-muted-foreground">Otomatis mengikuti Payment Term.</p>
                            {form.errors.ProposedTOP && <p className="mt-1 text-[11px] text-danger-text">{form.errors.ProposedTOP}</p>}
                        </div>
                        <div>
                            <label className="mb-1 block text-xs font-semibold text-muted-foreground">Justification</label>
                            <NativeSelect value={form.data.JustificationID}
                                onChange={(e) => form.setData('JustificationID', e.target.value)} className={inp}>
                                <option value="">Select Justification</option>
                                {(options?.justifications ?? []).map((j) => <option key={j.id} value={j.id}>{j.name}</option>)}
                            </NativeSelect>
                            {form.errors.JustificationID && <p className="mt-1 text-[11px] text-danger-text">{form.errors.JustificationID}</p>}
                        </div>
                    </div>

                    <div className="flex flex-wrap items-center justify-end gap-2 border-t border-border/40 pt-3.5">
                        {/* Print / Download — react-pdf port of legacy reportcreditceiling.php
                            (wired 2026-08-02; these were label-only before). */}
                        <p className="m-0 mr-auto text-[11px] text-muted-foreground">
                            {ccPdf.busy ? 'Menyiapkan dokumen…' : 'Print membuka PDF di tab baru · Download menyimpan berkas'}
                        </p>
                        <Button type="button" variant="outline" disabled={ccPdf.busy !== null}
                            onClick={ccPdf.print} title="Print Credit Ceiling">
                            {ccPdf.busy === 'print'
                                ? <Loader2 className="mr-1.5 size-3.5 animate-spin" />
                                : <Printer className="mr-1.5 size-3.5" />}Print
                        </Button>
                        <Button type="button" variant="outline" disabled={ccPdf.busy !== null}
                            onClick={ccPdf.download} title="Download Credit Ceiling">
                            {ccPdf.busy === 'download'
                                ? <Loader2 className="mr-1.5 size-3.5 animate-spin" />
                                : <Download className="mr-1.5 size-3.5" />}Download
                        </Button>
                        <Button type="submit" disabled={form.processing} className={PRIMARY_BTN}>
                            {form.processing ? <><Loader2 className="size-3.5 animate-spin" /> Menyimpan…</> : <><Send className="size-3.5" /> Revise / Recreate</>}
                        </Button>
                    </div>
                </form>
            </section>

            {/* Company Records — creditceilingrevise.php embeds the same 11 panes as the full CC
                stages, in their EDITABLE variants (listcompanycp1 / listcompanyreferences), so
                no readOnly override here: the creator is fixing their own request. */}
            {cc.companyId > 0 && (
                <CompanyTabs companyId={cc.companyId} preset="ccStage" />
            )}
        </div>
    );
}

Revise.layout = [AppLayout];
