import { useEffect, useMemo, useRef, useState } from 'react';
import { router } from '@inertiajs/react';
import { ArrowDown, ArrowUp, ChevronsUpDown, Pencil, RotateCcw, Search } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { ListFooter } from '@/Components/Table/ListFooter';
import { CreateActionButton } from '@/Components/Table/CreateActionButton';
import { SelectPill } from '@/Components/MenuQuotations/QuotationListPage/QuotationListPills';
import { ExportButton } from '@/lib/excel/ExportButton';
import { useColumnPrefs } from '@/lib/useColumnPrefs';
import { useResizableColumns, ColumnResizeGrip } from '@/lib/useResizableColumns';

// ─────────────────────────────────────────────────────────────────────────────
// Flat lot list — wires legacy listsamplesall.php (All Stock, canExport) and
// listsamples.php (Stock Details, no export). Server-driven: filter/sort/paginate
// all go through StockSampleController@index. Rendered from:
//   Inertia::render('MenuStockSample/StockSamples/AllStock', { rows, filters, options, view })
// Divergence from legacy's Name dropdown: name search is folded into the free-text
// search box (covers name/kode/lot/satuan/remark). See GH follow-up.
// ─────────────────────────────────────────────────────────────────────────────

// Sortable data columns (default order left→right). No + Edit are fixed non-sortable
// columns pinned outside the drag-reorderable set.
const NO_W = 60;
const EDIT_W = 64;
const COLUMN_DEFS = [
    { id: 'principal', label: 'Principal Name' },
    { id: 'category', label: 'Category Name' },
    { id: 'kode', label: 'Item Code' },
    { id: 'nama', label: 'Item Name', required: true }, // row anchor
    { id: 'lot', label: 'Lot Number' },
    { id: 'expiry', label: 'Expiry Date' },
    { id: 'qty', label: 'Quantity' },
    { id: 'satuan', label: 'Unit' },
    { id: 'masuk', label: 'Date In' },
    { id: 'ket', label: 'Remark' },
];
// Per-column td classes — every data cell renders dash(s[id]); Remark also gets a hover title.
const TD_CLASS = {
    principal: 'font-semibold text-card-foreground',
    category: 'text-muted-foreground',
    kode: 'tabular-nums text-muted-foreground',
    nama: 'font-semibold text-card-foreground',
    lot: 'text-muted-foreground',
    expiry: 'tabular-nums text-muted-foreground',
    qty: 'text-right tabular-nums text-foreground',
    satuan: 'text-muted-foreground',
    masuk: 'tabular-nums text-muted-foreground',
    ket: 'max-w-[200px] truncate text-muted-foreground',
};
const COL_W = {
    principal: 200, category: 150, kode: 110, nama: 220, lot: 130,
    expiry: 130, qty: 110, satuan: 100, masuk: 150, ket: 200,
};
const COL_W_FALLBACK = 150;
const NUM_COLS = new Set(['kode', 'expiry', 'qty', 'masuk']);

const EMPTY_PAGINATOR = { data: [], current_page: 1, last_page: 1, per_page: 10, from: 0, to: 0, total: 0 };
const dash = (v) => (v === null || v === undefined || v === '') ? <span className="text-muted-foreground/40">-</span> : v;

export default function StockSampleAllStock({ rows = EMPTY_PAGINATOR, filters = {}, options = {}, view = {}, canCreate = false }) {
    const data = rows.data;
    const pageSize = filters.per_page || 10;
    const currentPage = rows.current_page;
    const totalPages = rows.last_page;
    const sortKey = filters.sort || 'nama';
    const sortDir = filters.dir || 'asc';

    const [quickQuery, setQuickQuery] = useState(filters.search || '');
    const [openPill, setOpenPill] = useState(null);
    const filterBarRef = useRef(null);
    const searchDebounce = useRef(null);

    useEffect(() => {
        if (!openPill) return undefined;
        const onDoc = (e) => { if (filterBarRef.current && !filterBarRef.current.contains(e.target)) setOpenPill(null); };
        document.addEventListener('mousedown', onDoc);
        return () => document.removeEventListener('mousedown', onDoc);
    }, [openPill]);

    const routeName = view.key === 'details' ? 'stock-samples.details' : 'stock-samples.all';

    const buildParams = (overrides = {}) => {
        const params = {};
        const val = (k, def) => overrides[k] ?? filters[k] ?? def ?? '';
        const search = overrides.search ?? quickQuery;
        if (search) params.search = search;
        ['status', 'principal', 'category', 'name'].forEach((k) => { const v = val(k); if (v) params[k] = v; });
        const sort = val('sort', 'nama');
        const dir = val('dir', 'asc');
        if (sort !== 'nama') params.sort = sort;
        if (dir !== 'asc') params.dir = dir;
        const perPage = overrides.per_page ?? pageSize;
        if (perPage && Number(perPage) !== 10) params.per_page = perPage;
        const page = overrides.page ?? currentPage;
        if (page && Number(page) !== 1) params.page = page;
        return params;
    };
    // only: — see Index.jsx. This page serves both /all and /details through routeName.
    const go = (overrides) => router.get(route(routeName), buildParams(overrides), {
        only: ['rows', 'filters'],
        preserveState: true, preserveScroll: true, replace: true,
    });

    const onSearchChange = (v) => {
        setQuickQuery(v);
        clearTimeout(searchDebounce.current);
        searchDebounce.current = setTimeout(() => go({ search: v, page: 1 }), 300);
    };
    const setFilter = (key, value) => { setOpenPill(null); go({ [key]: value, page: 1 }); };
    const onSort = (key) => {
        const nextDir = sortKey === key && sortDir === 'asc' ? 'desc' : 'asc';
        go({ sort: key, dir: nextDir, page: 1 });
    };
    const anyFilter = quickQuery || filters.status || filters.principal || filters.category || filters.name;
    const clearFilters = () => {
        setQuickQuery('');
        setOpenPill(null);
        go({ search: '', status: '', principal: '', category: '', name: '', page: 1 });
    };

    // Export params = the live filter state (empties are dropped by the export hook).
    const exportParams = { search: filters.search, status: filters.status, principal: filters.principal, category: filters.category, name: filters.name };

    const { widthOf, startResize, resizingId, resizeRef } = useResizableColumns(COL_W, COL_W_FALLBACK);
    // Column order — persisted; headers are drag-to-reorder (No / Edit stay pinned outside the set).
    const prefs = useColumnPrefs('stockSampleAllStockColumns_v1', COLUMN_DEFS, { resizeGuardRef: resizeRef });
    const tableWidth = useMemo(() => NO_W + EDIT_W + prefs.visibleCols.reduce((s, c) => s + widthOf(c.id), 0), [prefs.visibleCols, widthOf]);

    const SortIcon = ({ col }) => {
        if (sortKey !== col) return <ChevronsUpDown className="size-3 opacity-40" />;
        return sortDir === 'asc' ? <ArrowUp className="size-3" /> : <ArrowDown className="size-3" />;
    };

    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">
                    <span>Stock Sample</span>
                    <span aria-hidden="true">›</span>
                    <span className="text-foreground">{view.title || 'All Stock'}</span>
                </p>
                <div className="flex items-start justify-between gap-4">
                    <h1 className="m-0 text-2xl font-bold leading-[1.15] tracking-tight text-card-foreground">{view.title || 'All Stock'}</h1>
                    <CreateActionButton canCreate={canCreate} label="Insert Sample" href={route('stock-samples.create')} />
                </div>
            </header>

            <article className="overflow-hidden rounded-xl border border-border bg-card shadow-sm">
                <div ref={filterBarRef} className="flex flex-wrap items-center gap-2.5 border-b border-border/50 px-5 py-4">
                    <label className="relative inline-flex h-8 min-w-[200px] max-w-[320px] flex-1 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">
                        <Search aria-hidden="true" className="size-3.5 shrink-0" />
                        <input type="search" placeholder="Search principal, product, lot, code…" autoComplete="off"
                            value={quickQuery} onChange={(e) => onSearchChange(e.target.value)}
                            className="min-w-0 flex-1 bg-transparent text-[12.5px] font-medium text-foreground outline-none placeholder:text-muted-foreground/70" />
                    </label>

                    <SelectPill label="Status" value={filters.status || ''} options={options.statuses || []}
                        open={openPill === 'status'} onToggle={() => setOpenPill(openPill === 'status' ? null : 'status')} onPick={(v) => setFilter('status', v)} />
                    <SelectPill label="Principal" value={filters.principal || ''} options={options.principals || []}
                        open={openPill === 'principal'} onToggle={() => setOpenPill(openPill === 'principal' ? null : 'principal')} onPick={(v) => setFilter('principal', v)} />
                    <SelectPill label="Category" value={filters.category || ''} options={options.categories || []}
                        open={openPill === 'category'} onToggle={() => setOpenPill(openPill === 'category' ? null : 'category')} onPick={(v) => setFilter('category', v)} />

                    {anyFilter && (
                        <button type="button" onClick={clearFilters}
                            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 className="ml-auto flex items-center gap-3">
                        {view.canExport && (
                            <ExportButton
                                specKey="stockAllExport"
                                url={route('stock-samples.all.export-data')}
                                params={exportParams}
                                label="Export to Excel"
                                className="h-8 px-3 text-xs"
                            />
                        )}
                    </div>
                </div>

                <div className="px-5 pb-5 pt-4">
                    <div className="overflow-x-auto rounded-xl border border-border/40">
                        <table style={{ width: tableWidth }} className="w-full table-fixed border-collapse [&_tbody_td]:overflow-hidden">
                            <colgroup>
                                <col style={{ width: NO_W }} />
                                {prefs.visibleCols.map((col) => <col key={col.id} style={{ width: widthOf(col.id) }} />)}
                                <col style={{ width: EDIT_W }} />
                            </colgroup>
                            <thead>
                                <tr className="border-b border-border [&_th]:whitespace-nowrap [&_th]:bg-secondary/50 [&_th]:px-3.5 [&_th]:py-3 [&_th]:text-left [&_th]:text-[11px] [&_th]:font-semibold [&_th]:uppercase [&_th]:tracking-wide [&_th]:text-muted-foreground">
                                    <th className="!text-right">No</th>
                                    {prefs.visibleCols.map(({ id, label }) => (
                                        <th key={id} {...prefs.dragProps(id)} className={`group/col relative ${NUM_COLS.has(id) ? '!text-right' : ''} ${prefs.dragClass(id)}`}>
                                            <button type="button" onClick={() => onSort(id)}
                                                className={`inline-flex items-center gap-1 uppercase tracking-wide hover:text-foreground ${NUM_COLS.has(id) ? 'flex-row-reverse' : ''} ${sortKey === id ? 'text-foreground' : ''}`}>
                                                {label}<SortIcon col={id} />
                                            </button>
                                            <ColumnResizeGrip onMouseDown={(e) => startResize(e, id)} active={resizingId === id} />
                                        </th>
                                    ))}
                                    <th className="!text-right">Edit</th>
                                </tr>
                            </thead>
                            <tbody className="[&_td]:whitespace-nowrap [&_td]:border-b [&_td]:border-border/60 [&_td]:px-3.5 [&_td]:py-[16px] [&_td]:text-[12px] [&_td]:text-foreground [&_tr:nth-child(even)_td]:bg-secondary/25 [&_tr:hover_td]:bg-secondary/60 [&_tr:last-child_td]:border-b-0">
                                {data.length === 0 ? (
                                    <tr><td colSpan={prefs.visibleCols.length + 2} className="!bg-transparent px-4 py-12 text-center text-[13px] text-muted-foreground">No samples match your filter.</td></tr>
                                ) : data.map((s, i) => (
                                    <tr key={s.id} className="cursor-pointer"
                                        onClick={(e) => { if (e.target.closest('a,button,input,label')) return; router.visit(route('stock-samples.edit', s.id)); }}>
                                        <td className="text-right tabular-nums text-muted-foreground">{(rows.from || 0) + i}</td>
                                        {prefs.visibleCols.map((col) => (
                                            <td key={col.id} className={TD_CLASS[col.id]} title={col.id === 'ket' ? (s.ket || undefined) : undefined}>
                                                {dash(s[col.id])}
                                            </td>
                                        ))}
                                        <td className="text-right">
                                            <button type="button" onClick={() => router.visit(route('stock-samples.edit', s.id))}
                                                aria-label="Edit sample" title="Edit"
                                                className="inline-grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-primary/10 hover:text-primary">
                                                <Pencil className="size-3.5" />
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>

                <ListFooter
                    page={currentPage} totalPages={totalPages} onPage={(p) => go({ page: p })}
                    pageSize={Number(pageSize)} onPageSize={(n) => go({ per_page: n, page: 1 })} pageSizeOptions={[10, 25, 50, 100]}
                    total={rows.total} itemLabel="samples" />
            </article>
        </section>
    );
}

StockSampleAllStock.layout = [AppLayout];
