import { Link, useForm, useHttp } from '@inertiajs/react'
import { useEffect, useRef, useState } from 'react'
import { ChevronDown, Pencil, Trash2, Loader2 } from 'lucide-react'
import AppLayout from '@/Layouts/AppLayout'
import { SearchableSelect } from '@/Components/Form/SearchableSelect'
import { FloatingField } from '@/Components/Proto/UI/FloatingField'
import { Pill } from '@/Components/Proto/UI/Pill'
import { useToast } from '@/Components/Toast'
import ComplainItemModal from '@/Components/MenuComplaintAndReturns/ComplainItemModal'

// Complaint & Returns — Create for Others (menu 325, Q14: rebuilt properly). Same UI shell as the
// main Create (Proto/Complaints/Create.jsx faithful port: numbered section cards, collapse buttons,
// Pill eyebrows, the richer Details table + totals) — the ONE difference this screen carries is the
// on-behalf cascade in Section 1: you pick the Division and the Sales user FIRST, then the Company
// (scoped to that Sales) — where the main Create derives Division from a company-first pick and has
// no Sales field (the creator IS the salesperson). The DATA layer is unchanged from the Phase-8
// build: every effect/endpoint/submit is the real wiring, only re-skinned. No file-attachment field
// here (this controller hardcodes empty Upload* — it never reads one), so none is shown.

const formatIdrPlain = (n) => n?.toLocaleString('id-ID', { maximumFractionDigits: 0 }) || '0'
const formatUsdPlain = (n) => n?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '0.00'

const SECTION_CARD = 'h-full min-w-0 flex flex-col overflow-visible rounded-xl border border-border bg-card shadow-sm'
const SECTION_HEADER = 'grid grid-cols-[auto_1fr_auto_auto] items-center gap-3 border-b border-border min-h-[66px] p-[18px_24px]'
const SECTION_NUM = 'inline-grid size-8 place-items-center rounded-md bg-accent text-[13px] font-bold text-primary [letter-spacing:-0.01em]'
const SECTION_TITLE = 'm-0 text-base font-bold leading-tight text-card-foreground [letter-spacing:-0.005em]'
const SECTION_SUBTITLE = 'mt-0.5 text-[11px] text-muted-foreground'
const EYEBROW = 'flex items-center justify-between gap-3 mb-3.5'
const EYEBROW_TITLE = 'm-0 text-[13px] font-extrabold text-card-foreground'
const DATA_BLOCK = 'mt-3.5 border-t border-dashed border-border pt-3 [&>span]:text-[10px] [&>span]:font-extrabold [&>span]:uppercase [&>span]:tracking-[0.025em] [&>span]:text-muted-foreground [&_p]:mt-1 [&_p]:min-h-[18px] [&_p]:italic [&_p]:text-muted-foreground'
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 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105'
const OUTLINE_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'

function useCollapsible(initial = false) {
    const [collapsed, setCollapsed] = useState(initial)
    return { collapsed, toggle: () => setCollapsed((v) => !v) }
}

function CollapseButton({ onClick, collapsed, label }) {
    return (
        <button type="button" aria-label={label} aria-expanded={!collapsed} onClick={onClick}
            className="inline-grid size-7.5 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-secondary hover:text-card-foreground">
            <ChevronDown aria-hidden="true" size={16} className={`transition-transform ${collapsed ? '' : 'rotate-180'}`} />
        </button>
    )
}

export default function Create({ divisions, complainTypes, complainReasons, principals, quotationPacks, satuans }) {
    const { show: showToast } = useToast()
    const form = useForm({
        DivisionID: null, UserIDSales: null, CompanyID: null, CompanyCPID: null,
        ComplainTypeID: null, ComplainReasonID: null,
        ComplainDate: new Date().toISOString().slice(0, 10),
        CompanyAddress: '', Telp: '', lines: [],
    })
    const [itemModalOpen, setItemModalOpen] = useState(false)
    // null = the modal is in add mode; a line = edit mode for that row.
    const [editingLine, setEditingLine] = useState(null)
    const customerSection = useCollapsible()
    const headerSection = useCollapsible()
    const detailsSection = useCollapsible()

    const [salesUsers, setSalesUsers] = useState([])
    const salesHttp = useHttp({})
    const divisionRef = useRef(null)
    useEffect(() => {
        salesHttp.cancel(); setSalesUsers([])
        form.setData('UserIDSales', null)
        if (!form.data.DivisionID) return
        divisionRef.current = form.data.DivisionID
        const requested = form.data.DivisionID
        salesHttp.get(route('complaints.create-others.options.users-by-division', requested), {
            onSuccess: (resp) => { if (divisionRef.current === requested) setSalesUsers(Array.isArray(resp) ? resp : []) },
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [form.data.DivisionID])

    const [companies, setCompanies] = useState([])
    const companiesHttp = useHttp({})
    const salesRef = useRef(null)
    useEffect(() => {
        companiesHttp.cancel(); setCompanies([])
        form.setData('CompanyID', null)
        if (!form.data.UserIDSales) return
        salesRef.current = form.data.UserIDSales
        const requested = form.data.UserIDSales
        companiesHttp.get(route('complaints.create-others.options.companies-by-sales', requested), {
            onSuccess: (resp) => { if (salesRef.current === requested) setCompanies(Array.isArray(resp) ? resp : []) },
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [form.data.UserIDSales])

    const [contacts, setContacts] = useState([])
    const contactsHttp = useHttp({})
    const companyRef = useRef(null)
    useEffect(() => {
        contactsHttp.cancel(); setContacts([])
        form.setData('CompanyCPID', null)
        if (!form.data.CompanyID) return
        companyRef.current = form.data.CompanyID
        const requested = form.data.CompanyID
        contactsHttp.get(route('complaints.options.company-cps', requested), {
            onSuccess: (resp) => { if (companyRef.current === requested) setContacts(Array.isArray(resp) ? resp : []) },
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [form.data.CompanyID])

    // DivisionID is chosen directly on this form (unlike the main Create, where it's derived
    // from the selected Company) — reuse the same applications-by-division cascade endpoint.
    const [applications, setApplications] = useState([])
    const appsHttp = useHttp({})
    useEffect(() => {
        appsHttp.cancel(); setApplications([])
        if (!form.data.DivisionID) return
        const requested = form.data.DivisionID
        appsHttp.get(route('complaints.options.applications-by-division', requested), {
            onSuccess: (resp) => setApplications(Array.isArray(resp) ? resp : []),
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [form.data.DivisionID])

    const selectedType = complainTypes.find((t) => t.ID === form.data.ComplainTypeID)
    const isRefund = selectedType?.Name === 'Refund'
    const selectedContact = contacts.find((c) => c.id === form.data.CompanyCPID)

    // Add/edit share one modal — same shape as the Quotations Create form.
    const openAddItem = () => { setEditingLine(null); setItemModalOpen(true) }
    const openEditItem = (line) => { setEditingLine(line); setItemModalOpen(true) }
    const closeItemModal = () => { setItemModalOpen(false); setEditingLine(null) }
    // Edit mode replaces the matching line in place, keeping its _clientId so the row keeps
    // its React key and its position in the table; add mode appends.
    const upsertItem = (item) => {
        form.setData('lines', editingLine
            ? form.data.lines.map((l) => (l._clientId === editingLine._clientId ? { ...item, _clientId: editingLine._clientId } : l))
            : [...form.data.lines, item])
        closeItemModal()
    }
    const removeItem = (clientId) => form.setData('lines', form.data.lines.filter((l) => l._clientId !== clientId))

    const submit = (e) => {
        e?.preventDefault()
        form.post(route('complaints.create-others.store'), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        })
    }
    const err = (k) => (form.errors[k] ? <p className="mt-1 text-[11px] font-semibold text-destructive">{form.errors[k]}</p> : null)

    const grandUsd = form.data.lines.reduce((s, l) => s + (Number(l.UnitPriceUSD) || 0) * (Number(l.ComplainQuantity) || 0), 0)
    const grandIdr = form.data.lines.reduce((s, l) => s + (Number(l.UnitPriceUSD) || 0) * (Number(l.USDRate) || 0) * (Number(l.ComplainQuantity) || 0), 0)

    return (
        <>
            <section className="flex min-w-0 flex-col gap-4.5">
                <header className="flex items-center justify-between gap-4">
                    <div>
                        <p className="m-0 mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                            <Link href={route('complaints.index')} className="text-muted-foreground no-underline hover:text-primary">Complaint &amp; Returns</Link>
                            <span aria-hidden="true">›</span>
                            <span className="text-foreground">Create for Others</span>
                        </p>
                        <h1 className="m-0 text-xl font-bold leading-tight text-card-foreground">Create Complaint &amp; Returns for Others</h1>
                    </div>
                    <div className="flex flex-wrap justify-end gap-2">
                        <button type="button" onClick={() => form.reset()} className={OUTLINE_BTN}>Reset</button>
                    </div>
                </header>

                <form onSubmit={submit} className="flex flex-col gap-4.5">
                    <section className="grid items-stretch gap-6 [grid-template-columns:minmax(0,1fr)_minmax(0,1fr)] max-[1180px]:grid-cols-1">
                        {/* ── Customer (on behalf of) ── */}
                        <article className={SECTION_CARD}>
                            <header className={SECTION_HEADER}>
                                <span className={SECTION_NUM}>1</span>
                                <div>
                                    <h2 className={SECTION_TITLE}>Customer</h2>
                                    <p className={SECTION_SUBTITLE}>On behalf of — division, sales &amp; contact</p>
                                </div>
                                <CollapseButton onClick={customerSection.toggle} collapsed={customerSection.collapsed} label="Collapse customer" />
                            </header>
                            {!customerSection.collapsed && (
                                <div className="flex-1 p-6">
                                    <div>
                                        <div className={EYEBROW}>
                                            <h3 className={EYEBROW_TITLE}>On Behalf Of</h3>
                                            <Pill tone="info">Sales</Pill>
                                        </div>
                                        <FloatingField as="select" label="Division *" value={form.data.DivisionID ?? ''}
                                            onChange={(e) => form.setData('DivisionID', Number(e.target.value) || null)}
                                            options={[{ value: '', label: 'Select Division' }, ...divisions.map((d) => ({ value: d.ID, label: d.DivisionName }))]} />
                                        {err('DivisionID')}
                                        <div className="mt-3.5">
                                            <SearchableSelect label="Sales *" placeholder={form.data.DivisionID ? 'Select Sales' : 'Select Division first'}
                                                disabled={!form.data.DivisionID} required
                                                options={salesUsers} value={form.data.UserIDSales} onChange={(v) => form.setData('UserIDSales', v)}
                                                searchPlaceholder="Search sales" emptyText="No sales found" />
                                            {err('UserIDSales')}
                                        </div>
                                    </div>

                                    <div className="mt-7 border-t border-border pt-6">
                                        <div className={EYEBROW}>
                                            <h3 className={EYEBROW_TITLE}>Company</h3>
                                            <Pill tone="info">Customer</Pill>
                                        </div>
                                        <SearchableSelect label="Company *" placeholder={form.data.UserIDSales ? 'Select Company' : 'Select Sales first'}
                                            disabled={!form.data.UserIDSales} required
                                            options={companies} value={form.data.CompanyID} onChange={(v) => form.setData('CompanyID', v)}
                                            searchPlaceholder="Search company" emptyText="No companies found" />
                                        {err('CompanyID')}
                                        <div className="mt-3.5">
                                            <FloatingField as="textarea" rows={1} label="Company Address" value={form.data.CompanyAddress}
                                                onChange={(e) => form.setData('CompanyAddress', e.target.value)} />
                                        </div>
                                        <div className="mt-3.5">
                                            <FloatingField label="Telp" type="text" value={form.data.Telp}
                                                onChange={(e) => form.setData('Telp', e.target.value)} />
                                        </div>
                                    </div>

                                    <div className="mt-7 border-t border-border pt-6">
                                        <div className={EYEBROW}>
                                            <h3 className={EYEBROW_TITLE}>Contact Person</h3>
                                            <Pill tone="info">Contact</Pill>
                                        </div>
                                        <SearchableSelect label="Contact Person *" placeholder={form.data.CompanyID ? 'Select Contact Person' : 'Select Company first'}
                                            disabled={!form.data.CompanyID} required
                                            options={contacts} value={form.data.CompanyCPID} onChange={(v) => form.setData('CompanyCPID', v)}
                                            searchPlaceholder="Search contact" emptyText="No contacts found" />
                                        {err('CompanyCPID')}
                                        <div className={DATA_BLOCK}>
                                            <span>Contact Info</span>
                                            <p>{selectedContact ? `${selectedContact.name}${selectedContact.subtext ? ' · ' + selectedContact.subtext : ''}` : 'No contact selected'}</p>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </article>

                        {/* ── Complaint Header ── */}
                        <article className={SECTION_CARD}>
                            <header className={SECTION_HEADER}>
                                <span className={SECTION_NUM}>2</span>
                                <div>
                                    <h2 className={SECTION_TITLE}>Complaint Header</h2>
                                    <p className={SECTION_SUBTITLE}>Type, reason &amp; date</p>
                                </div>
                                <CollapseButton onClick={headerSection.toggle} collapsed={headerSection.collapsed} label="Collapse header" />
                            </header>
                            {!headerSection.collapsed && (
                                <div className="flex-1 p-6">
                                    <div>
                                        <div className={EYEBROW}>
                                            <h3 className={EYEBROW_TITLE}>Classification</h3>
                                            <Pill tone="info">Type</Pill>
                                        </div>
                                        <FloatingField as="select" label="Complaint Type *" value={form.data.ComplainTypeID ?? ''}
                                            onChange={(e) => form.setData('ComplainTypeID', Number(e.target.value) || null)}
                                            options={[{ value: '', label: 'Select Complaint Type' }, ...complainTypes.map((t) => ({ value: t.ID, label: t.Name }))]} />
                                        {err('ComplainTypeID')}
                                        <div className="mt-3.5">
                                            <FloatingField as="select" label="Complaint Reason *" value={form.data.ComplainReasonID ?? ''}
                                                onChange={(e) => form.setData('ComplainReasonID', Number(e.target.value) || null)}
                                                options={[{ value: '', label: 'Select Complaint Reason' }, ...complainReasons.map((r) => ({ value: r.ID, label: r.ReasonName }))]} />
                                            {err('ComplainReasonID')}
                                        </div>
                                    </div>

                                    <div className="mt-7 border-t border-border pt-6">
                                        <div className={EYEBROW}>
                                            <h3 className={EYEBROW_TITLE}>Schedule</h3>
                                            <Pill tone="info">Meta</Pill>
                                        </div>
                                        <FloatingField label="Complaint Date *" type="date" value={form.data.ComplainDate}
                                            onChange={(e) => form.setData('ComplainDate', e.target.value)} />
                                        <p className="mx-0 mb-0 mt-1.5 text-[10px] font-medium italic text-muted-foreground">Ex: 2016-03-29 (YYYY-MM-DD)</p>
                                        {err('ComplainDate')}
                                    </div>
                                </div>
                            )}
                        </article>
                    </section>

                    {/* ── Details ── */}
                    <article className={SECTION_CARD}>
                        <header className={SECTION_HEADER}>
                            <span className={SECTION_NUM}>3</span>
                            <div>
                                <h2 className={SECTION_TITLE}>Details</h2>
                                <p className={SECTION_SUBTITLE}>Product items, pricing &amp; quantity</p>
                            </div>
                            <button type="button" disabled={!form.data.CompanyID} onClick={openAddItem}
                                className={`${PRIMARY_BTN} whitespace-nowrap disabled:cursor-not-allowed disabled:opacity-50`}>
                                + Add Barang
                            </button>
                            <CollapseButton onClick={detailsSection.toggle} collapsed={detailsSection.collapsed} label="Collapse details" />
                        </header>
                        {!detailsSection.collapsed && (
                            <div className="flex-1 p-6">
                                {err('lines')}
                                {Object.keys(form.errors).some((k) => k.startsWith('lines.')) && (
                                    <ul className="mb-3 space-y-0.5 rounded-lg border border-destructive/40 bg-destructive/5 p-2.5 text-[11px] font-semibold text-destructive">
                                        {Object.entries(form.errors)
                                            .filter(([k]) => k.startsWith('lines.'))
                                            .map(([k, msg]) => {
                                                const m = k.match(/^lines\.(\d+)\./)
                                                return <li key={k}>Item {m ? Number(m[1]) + 1 : ''}: {msg}</li>
                                            })}
                                    </ul>
                                )}
                                {form.data.lines.length === 0 ? (
                                    <div className="grid min-h-[72px] place-items-center rounded-[10px] border border-dashed border-input bg-card text-muted-foreground">
                                        No complaint items
                                    </div>
                                ) : (
                                    <div className="overflow-x-auto rounded-md">
                                        <table className="w-full min-w-[820px] overflow-hidden rounded-[10px] border-collapse [&_th]:border-b [&_th]:border-border [&_th]:bg-secondary [&_th]:p-2.5 [&_th]:text-left [&_th]:text-[10px] [&_th]:font-extrabold [&_th]:uppercase [&_th]:tracking-[0.025em] [&_th]:text-muted-foreground [&_td]:border-b [&_td]:border-border [&_td]:p-2.5 [&_td]:text-left [&_tbody_tr:hover]:bg-secondary/60">
                                            <thead>
                                                <tr>
                                                    <th>Principal</th>
                                                    <th>Product</th>
                                                    <th>Application</th>
                                                    <th>Packing</th>
                                                    <th>Lot No</th>
                                                    <th className="!text-right">Qty</th>
                                                    <th className="!text-right">Unit USD</th>
                                                    <th className="!text-right">USD Rate</th>
                                                    <th className="!text-right">Unit IDR</th>
                                                    <th className="!text-right">Total USD</th>
                                                    <th className="!text-right">Total IDR</th>
                                                    <th></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {form.data.lines.map((l) => {
                                                    const unitUsd = Number(l.UnitPriceUSD) || 0
                                                    const rate = Number(l.USDRate) || 0
                                                    const qty = Number(l.ComplainQuantity) || 0
                                                    const unitIdr = unitUsd * rate
                                                    return (
                                                        <tr key={l._clientId}>
                                                            <td>{l._principalName}</td>
                                                            <td>{l._productName}</td>
                                                            <td>{l._applicationName}</td>
                                                            <td>{l.QuantityPacking} {l._packingUnitName}</td>
                                                            <td>{l.BarangListID || '—'}</td>
                                                            <td className="!text-right">{qty} {l._complainUnitName}</td>
                                                            <td className="!text-right">${unitUsd.toFixed(2)}</td>
                                                            <td className="!text-right">{rate.toLocaleString('id-ID')}</td>
                                                            <td className="!text-right">Rp {formatIdrPlain(unitIdr)}</td>
                                                            <td className="!text-right">USD {formatUsdPlain(unitUsd * qty)}</td>
                                                            <td className="!text-right">Rp {formatIdrPlain(unitIdr * qty)}</td>
                                                            <td>
                                                                <div className="flex items-center gap-1.5">
                                                                    <button type="button" onClick={() => openEditItem(l)} aria-label="Edit item"
                                                                        className="inline-grid size-7 place-items-center rounded-full bg-success-bg font-extrabold text-success-text hover:brightness-95">
                                                                        <Pencil aria-hidden="true" className="size-3.5" />
                                                                    </button>
                                                                    <button type="button" onClick={() => removeItem(l._clientId)} aria-label="Remove item"
                                                                        className="inline-grid size-7 place-items-center rounded-full bg-danger-bg font-extrabold text-danger-text hover:brightness-95">
                                                                        <Trash2 aria-hidden="true" className="size-3.5" />
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    )
                                                })}
                                            </tbody>
                                            {form.data.lines.length > 1 && (
                                                <tfoot>
                                                    <tr className="font-bold">
                                                        <td colSpan={9} className="!text-right text-[11px] uppercase tracking-[0.04em] text-muted-foreground">Total</td>
                                                        <td className="!text-right">USD {formatUsdPlain(grandUsd)}</td>
                                                        <td className="!text-right">Rp {formatIdrPlain(grandIdr)}</td>
                                                        <td />
                                                    </tr>
                                                </tfoot>
                                            )}
                                        </table>
                                    </div>
                                )}
                            </div>
                        )}
                    </article>

                    {/* Form actions */}
                    <div className="flex items-center justify-between gap-4 pb-2">
                        <div className="flex flex-wrap gap-2.5">
                            <button type="submit" disabled={form.processing}
                                className={`${PRIMARY_BTN} disabled:cursor-not-allowed disabled:opacity-70`}>
                                {form.processing ? <><Loader2 className="size-3.5 animate-spin" /> Menyimpan…</> : 'Create Report'}
                            </button>
                        </div>
                        <Link href={route('complaints.index')} className={OUTLINE_BTN}>Cancel</Link>
                    </div>
                </form>
            </section>

            <ComplainItemModal
                open={itemModalOpen} onClose={closeItemModal} onAccept={upsertItem} initial={editingLine}
                principals={principals} quotationPacks={quotationPacks} satuans={satuans}
                applicationsEnabled={Boolean(form.data.DivisionID)} applicationOptions={applications}
                isRefund={isRefund}
            />
        </>
    )
}

Create.layout = [AppLayout]
