import { useMemo, useState } from 'react'
import { Link, router } from '@inertiajs/react'
import { ChevronRight, Eye, RotateCcw, Search, Settings } from 'lucide-react'
import { CustomizeColumnsModal } from '@/Components/Proto/Modals/CustomizeColumnsModal'
import { useColumnPrefs } from '@/lib/useColumnPrefs'
import { cn } from '@/lib/utils'
import AppLayout from '@/Layouts/AppLayout'
import { FilterPill } from '@/Components/ui/filter-pill'
import { HistoryPopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryPopover'
import { ListFooter } from '@/Components/Table/ListFooter'
import { TOOLBAR_ROW, TOOLBAR_GEAR, TOOLBAR_FILTERS } from '@/Components/Table'
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge'
import { DateText } from '@/Components/Proto/UI/DateText'
import { useResizableColumns, ColumnResizeGrip } from '@/lib/useResizableColumns'
import { useClientSort, SortButton } from '@/lib/ClientSort'
import { complaintStatusTone, complaintTypeTone } from '@/lib/complaintTone'

// Sortable columns — id → row value (alphabetical A→Z on first click).
const SORT_GETTERS = {
    reportNo: (c) => c.ComplainID,
    complainType: (c) => c.ComplainType,
    company: (c) => c.CompanyName,
    sales: (c) => c.Sales,
    creator: (c) => c.Creator,
    principal: (c) => c.PrincipalName,
    product: (c) => c.ProductName,
    division: (c) => c.DivisionName,
    application: (c) => c.ApplicationName,
    complainDate: (c) => c.ComplainDate,
    inputDate: (c) => c.InputDate,
}

// Complaint & Returns — one Review queue (menus 228-234, PRD §4.1). One page serves all six
// departments (SM/PM/CS/Finance/Accounting/Logistic) — the `dept` prop drives route + title.
// Faithful port of the proto Proto/Complaints/ReviewPmList.jsx (README rule 10): merged filter +
// list card, resizable columns, StatusBadge / DateText, History popover. Data is REAL (Inertia
// props); the mock lists were dropped — filters bind to the queue's own rows (rule 21).

// Data-driven columns — ⚙ opens CustomizeColumnsModal (hide/show + reorder), headers
// are also drag-to-reorder directly. Default widths feed the table-fixed layout.
const COLUMN_GROUPS = [{ id: 'queue', label: 'Queue' }]
const COLUMN_DEFS = [
    { id: 'reportNo', label: 'Report No', groupId: 'queue', required: true }, // row anchor
    { id: 'details', label: 'Details', groupId: 'queue' },
    { id: 'complainType', label: 'Complain Type', groupId: 'queue' },
    { id: 'company', label: 'Company Name', groupId: 'queue' },
    { id: 'sales', label: 'Sales', groupId: 'queue' },
    { id: 'creator', label: 'Creator', groupId: 'queue' },
    { id: 'principal', label: 'Principal', groupId: 'queue' },
    { id: 'product', label: 'Product', groupId: 'queue' },
    { id: 'division', label: 'Division', groupId: 'queue' },
    { id: 'application', label: 'Application', groupId: 'queue' },
    { id: 'complainDate', label: 'Complain Date', groupId: 'queue' },
    { id: 'inputDate', label: 'Input Date', groupId: 'queue' },
    { id: 'history', label: 'History', groupId: 'queue' },
]
const COL_W = {
    reportNo: 110, details: 110, complainType: 150, company: 220, sales: 150, creator: 150,
    principal: 160, product: 200, division: 130, application: 160, complainDate: 150, inputDate: 150, history: 110,
}
const COL_W_FALLBACK = 150

// Per-column cell renderer + td classes. `ctx.openDetail` navigates to the report.
const TD_CLASS = {
    reportNo: 'whitespace-nowrap !text-[13px] font-bold tabular-nums !text-primary',   // `!` wajib: [&_tbody_td]:text-foreground/text-[12px] di <table> = spesifisitas (0,1,2), menang atas kelas polos di td
    details: 'whitespace-nowrap text-center',
    complainType: 'whitespace-nowrap',
    company: 'whitespace-nowrap font-semibold text-foreground',
    sales: 'whitespace-nowrap text-muted-foreground',
    creator: 'whitespace-nowrap text-muted-foreground',
    principal: 'whitespace-nowrap text-foreground',
    product: 'whitespace-nowrap font-medium text-foreground',
    division: 'whitespace-nowrap',
    application: 'whitespace-nowrap text-[11px] text-muted-foreground',
    complainDate: 'whitespace-nowrap',
    inputDate: 'whitespace-nowrap',
    history: 'text-center',
}
function renderCell(c, colId, ctx) {
    switch (colId) {
        case 'reportNo': return c.ComplainID
        case 'details': return (
            <button type="button" onClick={() => ctx.openDetail(c)}
                className="group/link inline-flex items-center gap-1 text-[12px] font-bold text-primary transition-colors hover:underline">
                Details <ChevronRight className="size-3.5 transition-transform duration-200 group-hover/link:translate-x-0.5" aria-hidden="true" />
            </button>
        )
        case 'complainType': return c.ComplainType ? <StatusBadge tone={complaintTypeTone(c.ComplainType)}>{c.ComplainType}</StatusBadge> : <span className="text-muted-foreground">—</span>
        case 'company': return c.CompanyName || '—'
        case 'sales': return c.Sales || '—'
        case 'creator': return c.Creator || '—'
        case 'principal': return c.PrincipalName || '—'
        case 'product': return c.ProductName || '—'
        case 'division': return c.DivisionName ? <span className="inline-flex items-center rounded-full bg-secondary px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">{c.DivisionName}</span> : <span className="text-muted-foreground">—</span>
        case 'application': return c.ApplicationName || '—'
        case 'complainDate': return <DateText value={c.ComplainDate} />
        case 'inputDate': return <DateText value={c.InputDate} />
        case 'history': return (
            <HistoryPopover count={c.History?.length ?? 0} title="History">
                {(c.History ?? []).map((e, n) => (
                    <div key={n} className="flex flex-col gap-0.5 border-b border-border/50 pb-1.5 last:border-b-0">
                        <div className="flex items-center justify-between gap-2">
                            <StatusBadge tone={complaintStatusTone(e.status)}>{e.status}</StatusBadge>
                            <span className="shrink-0 text-[10px] font-medium tabular-nums text-muted-foreground">{e.tanggal}</span>
                        </div>
                        {e.user && <span className="text-[11px] font-semibold text-foreground">{e.user}</span>}
                        {e.remark && <span className="text-[11px] text-muted-foreground">{e.remark}</span>}
                    </div>
                ))}
            </HistoryPopover>
        )
        default: return '—'
    }
}

export default function Index({ lines, dept, deptName, filterOptions }) {
    // Every pill is MULTI-select (user decision 2026-08-20). Values are arrays of the raw
    // display NAMES, exactly what filterOptions carries — nothing is sent to the server, so
    // there is no id-space or comma-joined wire format to worry about here.
    const [division, setDivision] = useState([])
    const [sales, setSales] = useState([])
    const [company, setCompany] = useState([])
    const [principal, setPrincipal] = useState([])
    const [product, setProduct] = useState([])
    const [query, setQuery] = useState('')
    const [page, setPage] = useState(1)
    const [customizeOpen, setCustomizeOpen] = useState(false)
    const [pageSize, setPageSize] = useState(8)

    const rows = useMemo(() => {
        const s = query.trim().toLowerCase()
        return (lines ?? []).filter((c) => {
            if (division.length && !division.includes(c.DivisionName)) return false
            if (sales.length && !sales.includes(c.Sales)) return false
            if (company.length && !company.includes(c.CompanyName)) return false
            if (principal.length && !principal.includes(c.PrincipalName)) return false
            if (product.length && !product.includes(c.ProductName)) return false
            if (s && !`${c.ComplainID} ${c.ComplainType ?? ''} ${c.CompanyName ?? ''} ${c.Sales ?? ''} ${c.Creator ?? ''} ${c.PrincipalName ?? ''} ${c.ProductName ?? ''} ${c.DivisionName ?? ''} ${c.ApplicationName ?? ''}`.toLowerCase().includes(s)) return false
            return true
        })
    }, [lines, division, sales, company, principal, product, query])

    // Resizable columns — drag a header's right edge to resize.
    const { widthOf, startResize, resizingId, resizeRef } = useResizableColumns(COL_W, COL_W_FALLBACK)
    // Column order + visibility — ⚙ modal AND direct header drag, persisted per user.
    const prefs = useColumnPrefs('complaintReviewColumns_v1', COLUMN_DEFS, { resizeGuardRef: resizeRef })
    const tableWidth = useMemo(() => prefs.visibleCols.reduce((sum, col) => sum + widthOf(col.id), 0), [prefs.visibleCols, widthOf])

    const resetPage = () => setPage(1)
    const totalPages = Math.max(1, Math.ceil(rows.length / pageSize))
    const currentPage = Math.min(page, totalPages)
    const { sorted, sortKey, sortDir, toggleSort } = useClientSort(rows, SORT_GETTERS)
    const pageRows = sorted.slice((currentPage - 1) * pageSize, currentPage * pageSize)

    const openDetail = (c) => router.visit(route('complaints.review.show', [dept, c.ID]))

    return (
        <section className="flex min-w-0 flex-col gap-[18px]">
            <header>
                <p className="m-0 mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                    <Link href={route('complaints.review.index', dept)} className="no-underline hover:text-primary">Complain &amp; Returns</Link>
                    <span aria-hidden="true">›</span>
                    <span className="text-foreground">Review {deptName}</span>
                </p>
                <h1 className="m-0 text-xl font-bold leading-[1.2] text-card-foreground">Complaint &amp; Returns Report - Review {deptName}</h1>
            </header>

            {/* Main content area (list + optional configuration panel) */}
            <div className="flex min-w-0 flex-1 flex-col gap-[18px] lg:flex-row lg:items-start">
                {/* Filter bar + list — one merged card */}
                <article className="min-w-0 flex-1 overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
                    <div className={cn(TOOLBAR_ROW, 'border-b border-border/50 px-5 py-4')}>
                        <label className="relative inline-flex h-8 w-[260px] max-w-full items-center gap-2 rounded-full border border-transparent bg-muted/60 px-3.5 text-muted-foreground transition-colors hover:bg-muted focus-within:border-primary/40 focus-within:bg-card" aria-label="Search complaint">
                            <Search aria-hidden="true" className="size-3.5 shrink-0" />
                            <input type="search" placeholder="Search report, company, product…" autoComplete="off" value={query}
                                onChange={(e) => { setQuery(e.target.value); resetPage() }}
                                className="min-w-0 flex-1 bg-transparent text-[12.5px] font-medium text-foreground outline-none placeholder:text-muted-foreground/70" />
                        </label>
                        <button type="button" onClick={() => setCustomizeOpen(true)} title="Customize columns" aria-label="Customize columns"
                            className={TOOLBAR_GEAR}>
                            <Settings className="size-3.5" strokeWidth={2.5} />
                        </button>
                        <div className={TOOLBAR_FILTERS}>
                        <FilterPill label="Division" value={division} options={filterOptions?.divisions ?? []}
                            onChange={(v) => { setDivision(v); resetPage() }} />
                        <FilterPill label="Sales" value={sales} options={filterOptions?.sales ?? []}
                            onChange={(v) => { setSales(v); resetPage() }} />
                        <FilterPill label="Company" value={company} options={filterOptions?.companies ?? []}
                            onChange={(v) => { setCompany(v); resetPage() }} />
                        <FilterPill label="Principal" value={principal} options={filterOptions?.principals ?? []}
                            onChange={(v) => { setPrincipal(v); resetPage() }} />
                        <FilterPill label="Product Name" value={product} options={filterOptions?.products ?? []}
                            onChange={(v) => { setProduct(v); resetPage() }} />
                        {Boolean(query || division.length || sales.length || company.length || principal.length || product.length) && (
                            <button type="button" onClick={() => { setQuery(''); setDivision([]); setSales([]); setCompany([]); setPrincipal([]); setProduct([]); resetPage() }}
                                title="Reset all active filters"
                                className="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full px-2.5 text-[12.5px] font-semibold text-muted-foreground transition-colors hover:bg-danger/10 hover:text-danger-text">
                                <RotateCcw className="size-3.5" />
                                <span>Reset filters</span>
                            </button>
                        )}
                        </div>
                    </div>

                    <div className="overflow-x-auto">
                        <table style={{ minWidth: tableWidth }} className="w-full table-fixed border-separate border-spacing-0 [&_tbody_td]:overflow-hidden [&_tbody_td]:border-b [&_tbody_td]:border-border/50 [&_tbody_td]:px-3.5 [&_tbody_td]:py-[16px] [&_tbody_td]:align-middle [&_tbody_td]:text-[12px] [&_tbody_td]:text-foreground [&_tbody_tr:last-child_td]:border-b-0 [&_tbody_tr:hover_td]:bg-muted/30 [&_thead_th]:whitespace-nowrap [&_thead_th]:bg-muted/40 [&_thead_th]:border-b [&_thead_th]:border-border/70 [&_thead_th]:px-3.5 [&_thead_th]:py-3 [&_thead_th]:text-left [&_thead_th]:text-[11px] [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-wide [&_thead_th]:text-muted-foreground [&_th.text-center]:text-center [&_thead_th:first-child]:rounded-l-full [&_thead_th:first-child]:pl-7 [&_tbody_td:first-child]:pl-7 [&_thead_th:last-child]:rounded-r-full [&_tbody_td:last-child]:pr-5">
                            <colgroup>
                                {prefs.visibleCols.map((col) => <col key={col.id} style={{ width: widthOf(col.id) }} />)}
                            </colgroup>
                            <thead>
                                <tr>
                                    {prefs.visibleCols.map((col) => (
                                        <th key={col.id} {...prefs.dragProps(col.id)}
                                            className={`group/col relative ${(col.id === 'details' || col.id === 'history') ? '!text-center' : ''} ${prefs.dragClass(col.id)}`}>
                                            {SORT_GETTERS[col.id]
                                                ? <SortButton id={col.id} label={col.label} sortKey={sortKey} sortDir={sortDir} onToggle={toggleSort} />
                                                : col.label}
                                            <ColumnResizeGrip onMouseDown={(e) => startResize(e, col.id)} active={resizingId === col.id} />
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {pageRows.length === 0 ? (
                                    <tr>
                                        <td colSpan={prefs.visibleCols.length} className="px-4 py-10 text-center italic text-muted-foreground">No complaint reports match the filter.</td>
                                    </tr>
                                ) : (
                                    pageRows.map((c) => (
                                        <tr key={c.ID} onClick={() => openDetail(c)} className="cursor-pointer group/row">
                                            {prefs.visibleCols.map((col) => (
                                                <td key={col.id} className={TD_CLASS[col.id]}
                                                    onClick={(col.id === 'details' || col.id === 'history') ? (e) => e.stopPropagation() : undefined}>
                                                    {renderCell(c, col.id, { openDetail })}
                                                </td>
                                            ))}
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>

                    <ListFooter
                        page={currentPage} totalPages={totalPages} onPage={setPage}
                        pageSize={pageSize} onPageSize={(n) => { setPageSize(n); setPage(1) }} pageSizeOptions={[8, 15, 25, 50]}
                        total={rows.length} itemLabel="results" />
                </article>
            </div>

            <CustomizeColumnsModal
                open={customizeOpen}
                onClose={() => setCustomizeOpen(false)}
                groups={COLUMN_GROUPS}
                definitions={COLUMN_DEFS}
                state={prefs.columnState}
                onApply={prefs.applyColumns}
                onReset={prefs.resetColumns}
            />
        </section>
    )
}

Index.layout = [AppLayout]
