import { useMemo, useRef, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { ArrowDown, ArrowUp, CalendarDays, ChevronDown, ChevronsUpDown, RotateCcw, Search, Settings } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { cn } from '@/lib/utils';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { CustomizeColumnsModal } from '@/Components/Proto/Modals/CustomizeColumnsModal';
import { useResizableColumns, ColumnResizeGrip } from '@/lib/useResizableColumns';
import { ListFooter } from '@/Components/Table/ListFooter';
import { useStickyColShadow } from '@/lib/useStickyColShadow';

const COLUMN_GROUPS = [
    { id: 'identifiers', label: 'Identifiers' },
    { id: 'metadata', label: 'Metadata' },
    { id: 'order', label: 'Order & Dates' },
];
const COLUMN_DEFS = [
    { id: 'id', label: 'Qt No', groupId: 'identifiers', required: true },
    { id: 'company', label: 'Company Name', groupId: 'identifiers', required: true },
    { id: 'status', label: 'Quotation Status', groupId: 'identifiers' },
    { id: 'feedback', label: 'Feedback Status', groupId: 'identifiers' },
    { id: 'creator', label: 'Creator', groupId: 'metadata' },
    { id: 'sales', label: 'Sales', groupId: 'metadata' },
    { id: 'division', label: 'Division', groupId: 'metadata' },
    { id: 'industry', label: 'Industry', groupId: 'metadata' },
    { id: 'companyCategory', label: 'Company Category', groupId: 'metadata' },
    { id: 'tanggal', label: 'Tanggal', groupId: 'order' },
    { id: 'isOrder', label: 'Is Order', groupId: 'order' },
    { id: 'poNo', label: 'Customer PO No', groupId: 'order' },
    { id: 'poDate', label: 'Customer PO Date', groupId: 'order' },
    { id: 'deliveryDate', label: 'Delivery Date', groupId: 'order' },
    { id: 'comment', label: 'Comment', groupId: 'order' },
    { id: 'productList', label: 'Product List', groupId: 'order' },
];
const DEFAULT_VISIBLE = new Set(COLUMN_DEFS.filter((c) => c.id !== 'productList').map((c) => c.id));
const defaultColumnState = () => COLUMN_DEFS.map((d) => ({ id: d.id, visible: DEFAULT_VISIBLE.has(d.id) }));
// Default per-column pixel widths for the resizable table-fixed layout (overridable by drag).
const COL_W = {
    id: 90, company: 230, status: 150, feedback: 150, creator: 130, sales: 130,
    division: 120, industry: 150, companyCategory: 160, tanggal: 120, isOrder: 100,
    poNo: 150, poDate: 140, deliveryDate: 130, comment: 180, productList: 320,
};
const COL_W_FALLBACK = 150;
const STORAGE_KEY = 'quotationFeedbackColumnsState_v1';
function loadStoredState() {
    try {
        const raw = localStorage.getItem(STORAGE_KEY);
        if (!raw)
            return defaultColumnState();
        const parsed = JSON.parse(raw);
        const ids = new Set(parsed.map((c) => c.id));
        COLUMN_DEFS.forEach((d) => { if (!ids.has(d.id))
            parsed.push({ id: d.id, visible: DEFAULT_VISIBLE.has(d.id) }); });
        return parsed;
    }
    catch {
        return defaultColumnState();
    }
}

// Maps the real quotationstatus.StatusName to a StatusBadge tone.
const STATUS_TONES = {
    'Request': 'warning',
    'Approval SM': 'primary',
    'Approval PM': 'primary',
    'Revise': 'warning',
    'Reject': 'danger',
    'Cancel': 'danger',
    'Print': 'success',
    'Feedback': 'primary',
    'Process To Order': 'success',
    'Good Shipped': 'success',
    'Good Receive': 'success',
    'Update PO Number': 'neutral',
    'Update Delivery Fee': 'neutral',
    'Price Indication': 'neutral',
};
const statusTone = (status) => STATUS_TONES[status] || 'neutral';

const SORTABLE = new Set(['id', 'company', 'status', 'feedback', 'creator', 'sales', 'division', 'industry', 'tanggal', 'poNo', 'poDate', 'deliveryDate', 'comment']);

const isBlankDate = (v) => !v || v === '0000-00-00';

export default function QuotationFeedbackList({ quotations, filters, filterOptions }) {
    const rows = quotations.data;
    const sortKey = filters.sort || 'id';
    const sortDir = filters.dir || 'desc';
    const pageSize = filters.per_page || 10;

    const [quickQuery, setQuickQuery] = useState(filters.search || '');
    const [selectedDiv, setSelectedDiv] = useState(filters.division || '');
    const [selectedInd, setSelectedInd] = useState(filters.industry || '');
    const [selectedCreator, setSelectedCreator] = useState(filters.creator || '');
    const [selectedSales, setSelectedSales] = useState(filters.sales || '');
    const [isOrder, setIsOrder] = useState(Boolean(filters.is_order));
    const [dateFrom, setDateFrom] = useState(filters.date_from || '');
    const [dateTo, setDateTo] = useState(filters.date_to || '');
    // Sticky-column divider appears only while scrolled horizontally.
    const { scrollRef, shadowClass } = useStickyColShadow();
    const [activePill, setActivePill] = useState(null);

    const [columnState, setColumnState] = useState(loadStoredState);
    const [customizeOpen, setCustomizeOpen] = useState(false);
    const [dragColIdx, setDragColIdx] = useState(null);
    const [dragOverColIdx, setDragOverColIdx] = useState(null);
    const searchDebounce = useRef(null);

    const visibleCols = useMemo(() => columnState
        .filter((c) => c.visible)
        .map((c) => COLUMN_DEFS.find((d) => d.id === c.id))
        .filter(Boolean), [columnState]);

    // Resizable columns — drag a header's right edge (matches approval-pm quotation).
    const { widthOf, startResize, resizingId, resizeRef } = useResizableColumns(COL_W, COL_W_FALLBACK);
    const tableWidth = useMemo(() => visibleCols.reduce((s, c) => s + widthOf(c.id), 0), [visibleCols, widthOf]);

    const buildParams = (overrides = {}) => {
        const search = overrides.search ?? quickQuery;
        const division = overrides.division ?? selectedDiv;
        const industry = overrides.industry ?? selectedInd;
        const creator = overrides.creator ?? selectedCreator;
        const sales = overrides.sales ?? selectedSales;
        const order = overrides.is_order ?? isOrder;
        const from = overrides.date_from ?? dateFrom;
        const to = overrides.date_to ?? dateTo;
        const sort = overrides.sort ?? sortKey;
        const dir = overrides.dir ?? sortDir;
        const perPage = overrides.per_page ?? pageSize;
        const page = overrides.page ?? quotations.current_page;
        const params = {};
        if (search) params.search = search;
        if (division) params.division = division;
        if (industry) params.industry = industry;
        if (creator) params.creator = creator;
        if (sales) params.sales = sales;
        if (order) params.is_order = 1; // server defaults to OFF when absent (the legacy feedback menu link carries no ?IsOrder=on)
        if (from) params.date_from = from;
        if (to) params.date_to = to;
        if (sort && sort !== 'id') params.sort = sort;
        if (dir && dir !== 'desc') params.dir = dir;
        if (perPage && Number(perPage) !== 10) params.per_page = perPage;
        if (page && Number(page) !== 1) params.page = page;
        return params;
    };
    // Partial reload — see the note in MenuQuotations/GoodReceive/List.jsx. `filters`
    // stays in the allowlist because the sort/page-size state is read from it.
    const go = (overrides) => router.get(route('quotations.feedback'), buildParams(overrides), {
        preserveState: true, preserveScroll: true, replace: true,
        only: ['quotations', 'filters'],
    });

    const onSearchChange = (val) => {
        setQuickQuery(val);
        clearTimeout(searchDebounce.current);
        searchDebounce.current = setTimeout(() => go({ search: val, page: 1 }), 300);
    };

    const onSort = (key) => {
        let dir;
        if (sortKey === key)
            dir = sortDir === 'asc' ? 'desc' : 'asc';
        else
            dir = key === 'id' ? 'desc' : 'asc';
        go({ sort: key, dir, page: 1 });
    };

    const handleApplyColumns = (next) => {
        setColumnState(next);
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
        }
        catch { }
    };
    const handleResetColumns = () => {
        const def = defaultColumnState();
        try {
            localStorage.removeItem(STORAGE_KEY);
        }
        catch { }
        return def;
    };
    const reorderColumns = (fromIdx, toIdx) => {
        if (fromIdx === null || fromIdx === toIdx) return;
        const fromId = visibleCols[fromIdx]?.id;
        const toId   = visibleCols[toIdx]?.id;
        if (!fromId || !toId) return;
        setColumnState(prev => {
            const next = [...prev];
            const fi = next.findIndex(c => c.id === fromId);
            const ti = next.findIndex(c => c.id === toId);
            const [moved] = next.splice(fi, 1);
            next.splice(ti, 0, moved);
            try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch {}
            return next;
        });
    };

    const PILL_BTN = 'inline-flex h-8 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border border-border/50 bg-card px-3 text-[12.5px] font-semibold text-muted-foreground shadow-sm transition-colors hover:border-primary hover:text-primary';
    const PILL_ACTIVE = 'border-border-soft-strong bg-accent text-primary';
    const PILL_PANEL = 'absolute left-0 top-[calc(100%+6px)] z-50 max-h-60 min-w-45 overflow-y-auto rounded-xl border border-border bg-card shadow-[0_8px_24px_rgba(0,0,0,0.12)]';

    const renderSelectPill = (key, label, value, setValue, options) => {
        const hasVal = Boolean(value);
        return (
            <div className="relative">
                <button
                    type="button"
                    className={cn(PILL_BTN, hasVal && PILL_ACTIVE)}
                    onClick={() => { setActivePill(activePill === key ? null : key); }}
                >
                    <span>{hasVal ? `${label}: ${value}` : label}</span>
                    {hasVal ? (
                        <span className="inline-flex h-4 w-4 cursor-pointer items-center justify-center rounded-full bg-primary/18 text-[0.75rem] leading-none hover:bg-danger hover:text-white" role="button" aria-label="Clear" onClick={e => { e.stopPropagation(); setValue(''); setActivePill(null); go({ [key]: '', page: 1 }); }}>×</span>
                    ) : (
                        <ChevronDown aria-hidden="true" className="size-2.5" />
                    )}
                </button>
                {activePill === key && (
                    <div className={PILL_PANEL}>
                        <ul className="m-0 list-none py-1.5">
                            <li className={cn('cursor-pointer px-3.5 py-2.25 text-[0.8rem] font-medium text-card-foreground transition-colors hover:bg-secondary', !value && 'bg-accent font-bold text-primary')} onClick={() => { setValue(''); setActivePill(null); go({ [key]: '', page: 1 }); }}>All {label}</li>
                            {options.map(o => (
                                <li key={o} className={cn('cursor-pointer px-3.5 py-2.25 text-[0.8rem] font-medium text-card-foreground transition-colors hover:bg-secondary', value === o && 'bg-accent font-bold text-primary')} onClick={() => { setValue(o); setActivePill(null); go({ [key]: o, page: 1 }); }}>{o}</li>
                            ))}
                        </ul>
                    </div>
                )}
            </div>
        );
    };

    // Same pill design, but options are {id, name} and the request param is the id.
    const renderUserPill = (key, label, value, setValue, options) => {
        const hasVal = Boolean(value);
        const selectedName = hasVal ? (options.find(o => Number(o.id) === Number(value))?.name ?? value) : '';
        return (
            <div className="relative">
                <button
                    type="button"
                    className={cn(PILL_BTN, hasVal && PILL_ACTIVE)}
                    onClick={() => { setActivePill(activePill === key ? null : key); }}
                >
                    <span>{hasVal ? `${label}: ${selectedName}` : label}</span>
                    {hasVal ? (
                        <span className="inline-flex h-4 w-4 cursor-pointer items-center justify-center rounded-full bg-primary/18 text-[0.75rem] leading-none hover:bg-danger hover:text-white" role="button" aria-label="Clear" onClick={e => { e.stopPropagation(); setValue(''); setActivePill(null); go({ [key]: '', page: 1 }); }}>×</span>
                    ) : (
                        <ChevronDown aria-hidden="true" className="size-2.5" />
                    )}
                </button>
                {activePill === key && (
                    <div className={PILL_PANEL}>
                        <ul className="m-0 list-none py-1.5">
                            <li className={cn('cursor-pointer px-3.5 py-2.25 text-[0.8rem] font-medium text-card-foreground transition-colors hover:bg-secondary', !value && 'bg-accent font-bold text-primary')} onClick={() => { setValue(''); setActivePill(null); go({ [key]: '', page: 1 }); }}>All {label}</li>
                            {options.map(o => (
                                <li key={o.id} className={cn('cursor-pointer px-3.5 py-2.25 text-[0.8rem] font-medium text-card-foreground transition-colors hover:bg-secondary', Number(value) === Number(o.id) && 'bg-accent font-bold text-primary')} onClick={() => { setValue(o.id); setActivePill(null); go({ [key]: o.id, page: 1 }); }}>{o.name}</li>
                            ))}
                        </ul>
                    </div>
                )}
            </div>
        );
    };

    const renderIsOrderPill = () => (
        <button
            type="button"
            className={cn(PILL_BTN, isOrder && PILL_ACTIVE)}
            aria-pressed={isOrder}
            onClick={() => {
                const next = !isOrder;
                setIsOrder(next);
                go({ is_order: next, page: 1 });
            }}
        >
            <span>Is Order</span>
            {isOrder && <span aria-hidden="true">✓</span>}
        </button>
    );

    const renderDatePill = () => {
        const hasVal = Boolean(dateFrom || dateTo);
        const label = hasVal ? `Tanggal: ${dateFrom || '…'} – ${dateTo || '…'}` : 'Tanggal';
        return (
            <div className="relative">
                <button
                    type="button"
                    className={cn(PILL_BTN, hasVal && PILL_ACTIVE)}
                    onClick={() => { setActivePill(activePill === 'tanggal' ? null : 'tanggal'); }}
                >
                    <CalendarDays aria-hidden="true" className="size-3" />
                    <span>{label}</span>
                    {hasVal ? (
                        <span className="inline-flex h-4 w-4 cursor-pointer items-center justify-center rounded-full bg-primary/18 text-[0.75rem] leading-none hover:bg-danger hover:text-white" role="button" aria-label="Clear" onClick={e => { e.stopPropagation(); setDateFrom(''); setDateTo(''); setActivePill(null); go({ date_from: '', date_to: '', page: 1 }); }}>×</span>
                    ) : (
                        <ChevronDown aria-hidden="true" className="size-2.5" />
                    )}
                </button>
                {activePill === 'tanggal' && (
                    <div className={cn(PILL_PANEL, 'min-w-60 p-3.5')}>
                        <div className="flex flex-col gap-2.5">
                            <label className="flex flex-col gap-1 text-[0.72rem] font-semibold text-muted-foreground">
                                From
                                <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} className="h-8 rounded-lg border border-input bg-card px-2 text-xs text-foreground outline-none focus:border-primary" />
                            </label>
                            <label className="flex flex-col gap-1 text-[0.72rem] font-semibold text-muted-foreground">
                                To
                                <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} className="h-8 rounded-lg border border-input bg-card px-2 text-xs text-foreground outline-none focus:border-primary" />
                            </label>
                            <div className="flex justify-end gap-2 pt-1">
                                <button type="button" className="rounded-md border border-border bg-card px-2.5 py-1 text-xs font-medium text-foreground hover:border-primary hover:text-primary" onClick={() => { setDateFrom(''); setDateTo(''); setActivePill(null); go({ date_from: '', date_to: '', page: 1 }); }}>Clear</button>
                                <button type="button" className="rounded-md border border-primary bg-linear-to-br from-violet-500 to-primary px-2.5 py-1 text-xs font-bold text-primary-foreground" onClick={() => { setActivePill(null); go({ date_from: dateFrom, date_to: dateTo, page: 1 }); }}>Apply</button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        );
    };

    const renderCell = (q, colId) => {
        switch (colId) {
            case 'id': return <strong className="font-bold text-primary tabular-nums">#{q.id}</strong>;
            case 'company': return q.company ? <span className="text-[12px] font-semibold text-foreground">{q.company}</span> : '—';
            case 'status': return q.status ? <StatusBadge tone={statusTone(q.status)}>{q.status}</StatusBadge> : '—';
            case 'division': return q.division ? <span className="inline-flex items-center rounded-full bg-secondary px-2 py-0.5 text-[10px] font-bold uppercase text-muted-foreground">{q.division}</span> : '—';
            case 'feedback': return q.feedback ? <span className="text-muted-foreground">{q.feedback}</span> : '—';
            case 'creator': return q.creator || '—';
            case 'sales': return q.sales || '—';
            case 'industry': return q.industry ? <span className="text-muted-foreground">{q.industry}</span> : '—';
            case 'companyCategory': return q.companyCategory ? <span className="text-muted-foreground">{q.companyCategory}</span> : '—';
            case 'tanggal': return isBlankDate(q.tanggal) ? '—' : <span className="text-[11px] tabular-nums text-muted-foreground">{q.tanggal}</span>;
            case 'isOrder': return <span className="text-muted-foreground">{Number(q.isOrder) === 1 ? 'Yes' : 'No'}</span>;
            case 'poNo': return q.poNo ? <span className="text-[11px] tabular-nums text-muted-foreground">{q.poNo}</span> : '—';
            case 'poDate': return isBlankDate(q.poDate) ? '—' : <span className="text-[11px] tabular-nums text-muted-foreground">{q.poDate}</span>;
            case 'deliveryDate': return isBlankDate(q.deliveryDate) ? '—' : <span className="text-[11px] tabular-nums text-muted-foreground">{q.deliveryDate}</span>;
            case 'comment': return q.comment ? <span className="text-[11px] text-muted-foreground">{q.comment}</span> : '—';
            case 'productList': {
                const items = q.productList || [];
                if (!items.length) return '—';
                return (
                    <div className="flex flex-col gap-2">
                        {items.map((p, i) => (
                            <div key={i} className="leading-snug">
                                <strong className="font-semibold text-foreground">{p.productName}</strong>{' '}
                                <span className="text-[11px] text-muted-foreground tabular-nums">Pack: {p.packQty}{p.packName ? ` ${p.packName}` : ''};</span>{' '}
                                <span className="text-[11px] text-primary tabular-nums">Order: {p.orderQty}{p.orderSatuan ? ` ${p.orderSatuan}` : ''}</span>{' '}
                                <span className="text-[11px] text-primary font-medium tabular-nums">* ${p.unitUsd} (IDR {p.unitIdr})</span>{' '}
                                <span className="text-[11px] text-success-text font-medium tabular-nums">= ${p.totalUsd} (IDR {p.totalIdr})</span>
                            </div>
                        ))}
                    </div>
                );
            }
            default: return '—';
        }
    };

    const totalPages = quotations.last_page;
    const currentPage = quotations.current_page;

    return (
        <section className="flex min-w-0 flex-col gap-[18px]">
            <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('quotations.index')} className="no-underline hover:text-primary">Quotations</Link>
                        <span aria-hidden="true">›</span>
                        <span className="text-foreground">Feedback</span>
                    </p>
                    <h1 className="m-0 text-xl font-bold leading-[1.2] text-card-foreground">Feedback</h1>
                </div>
            </header>

            {/* ── Filter Pills Toolbar ─────────────────────────────────────────── */}
            {activePill && (
                <div className="fixed inset-0 z-49" onClick={() => setActivePill(null)} />
            )}

            <article className="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
              <div 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" aria-label="Search quotations">
                    <Search aria-hidden="true" className="size-3.5 shrink-0" />
                    <input
                        type="search"
                        placeholder="Search quotations..."
                        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>

                <div className="flex flex-1 flex-wrap items-center gap-2.5">
                    {renderSelectPill('division', 'Division', selectedDiv, setSelectedDiv, filterOptions?.divisions || [])}
                    {renderSelectPill('industry', 'Industry', selectedInd, setSelectedInd, filterOptions?.industries || [])}
                    {renderUserPill('creator', 'Creator', selectedCreator, setSelectedCreator, filterOptions?.creators || [])}
                    {renderUserPill('sales', 'Sales', selectedSales, setSelectedSales, filterOptions?.salesUsers || [])}
                    {renderIsOrderPill()}
                    {renderDatePill()}
                    {(quickQuery || selectedDiv || selectedInd || selectedCreator || selectedSales || dateFrom || dateTo || isOrder) && (
                        <button type="button" onClick={() => { setQuickQuery(''); setSelectedDiv(''); setSelectedInd(''); setSelectedCreator(''); setSelectedSales(''); setIsOrder(false); setDateFrom(''); setDateTo(''); go({ search: '', division: '', industry: '', creator: '', sales: '', is_order: false, date_from: '', date_to: '', page: 1 }); }}
                            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-0 sm:ml-auto inline-flex items-center gap-0.5">
                        <button type="button" onClick={() => setCustomizeOpen(true)} title="Customize columns" aria-label="Customize columns"
                            className="grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
                            <Settings aria-hidden="true" className="size-3.5" strokeWidth={2.5} />
                        </button>
                    </div>

                </div>              </div>

              <div className="px-5 pb-5 pt-4">
                <div ref={scrollRef} className="overflow-x-auto rounded-xl [background:linear-gradient(to_right,var(--card)_30%,transparent),linear-gradient(to_right,transparent,var(--card)_70%)_right,radial-gradient(farthest-side_at_0_50%,rgba(0,0,0,0.12),transparent),radial-gradient(farthest-side_at_100%_50%,rgba(0,0,0,0.12),transparent)_right] [background-attachment:local,local,scroll,scroll] [background-repeat:no-repeat] [background-size:40px_100%,40px_100%,14px_100%,14px_100%]">
                    <table style={{ width: tableWidth }} className={cn("w-full table-fixed border-separate border-spacing-0 [&_tbody_td]:overflow-hidden [&_td]:whitespace-nowrap [&_td]:px-3.5 [&_td]:py-3 [&_td]:text-left [&_td]:text-[12px] [&_td.col-edit]:text-center [&_td.col-no]:text-center [&_td.col-no]:font-extrabold [&_td.col-no]:text-muted-foreground [&_td.col-smart]:min-w-50 [&_td.col-smart]:border-l [&_td.col-smart]:border-border [&_td.col-smart]:px-3.5 [&_td.col-smart]:py-3 [&_td.col-smart]:align-middle [&_th]:whitespace-nowrap [&_th]:px-3.5 [&_th]:py-3 [&_th]:text-left [&_th]:text-[11px] [&_th.col-name]:sticky [&_th.col-name]:left-0 [&_th.col-name]:z-3 [&_th.col-smart]:min-w-50 [&_th.col-smart]:border-l [&_th.col-smart]:border-border [&_thead_.group-header_th]:border-b [&_thead_.group-header_th]:border-border [&_thead_.group-header_th]:bg-secondary [&_thead_.group-header_th]:px-3.5 [&_thead_.group-header_th]:py-1.5 [&_thead_.group-header_th]:text-center [&_thead_.group-header_th]:text-[10px] [&_thead_.group-header_th]:font-extrabold [&_thead_.group-header_th]:uppercase [&_thead_.group-header_th]:tracking-[0.04em] [&_thead_.group-header_th]:text-primary [&_thead_.group-header_th:not(:empty)]:bg-accent [&_thead_th]:sticky [&_thead_th]:top-0 [&_thead_th]:z-2 [&_thead_th]:bg-[color-mix(in_srgb,var(--color-secondary)_50%,var(--color-card))] [&_thead_th]:text-[11px] [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-wide [&_thead_th]:text-muted-foreground [&_thead_tr:first-child_th:first-child]:rounded-tl-full [&_thead_tr:first-child_th:first-child]:pl-7 [&_thead_tr:first-child_th:last-child]:rounded-tr-full [&_thead_tr:first-child_th:last-child]:pr-5 [&_thead_tr:last-child_th:first-child]:rounded-bl-full [&_thead_tr:last-child_th:first-child]:pl-7 [&_thead_tr:last-child_th:last-child]:rounded-br-full [&_thead_tr:last-child_th:last-child]:pr-5 [&_tbody_td]:border-b [&_tbody_td]:border-border/60 [&_tbody_td:last-child]:pr-5 [&_tbody_td]:px-3.5 [&_tbody_td]:py-[16px] [&_tbody_td]:text-[12px] [&_tbody_td]:text-card-foreground [&_tbody_td.col-address]:max-w-55 [&_tbody_td.col-name]:sticky [&_tbody_td.col-name]:left-0 [&_tbody_td.col-name]:z-1 [&_tbody_td.col-name]:bg-card [&_tbody_td.col-name]:font-bold [&_tbody_td.col-name]:text-card-foreground [&_tbody_td:first-child]:pl-7 [&_tbody_td:first-child]:text-foreground [&_tbody_tr:hover_td]:bg-secondary/60 [&_tbody_tr:hover_td.col-name]:bg-[color-mix(in_srgb,var(--color-secondary)_60%,var(--color-card))] [&_tbody_tr:nth-child(even)_td]:bg-secondary/25 [&_tbody_tr:nth-child(even)_td.col-name]:bg-[color-mix(in_srgb,var(--color-secondary)_25%,var(--color-card))]", shadowClass)}>
                        <colgroup>
                            {visibleCols.map((col) => <col key={col.id} style={{ width: widthOf(col.id) }} />)}
                        </colgroup>
                        <thead>
                            <tr>
                                {visibleCols.map((col, i) => {
                                    const k = SORTABLE.has(col.id) ? col.id : null;
                                    const isDragging = dragColIdx === i;
                                    const isDragOver = dragOverColIdx === i && dragColIdx !== i;
                                    return (
                                        <th
                                            key={col.id}
                                            draggable
                                            onDragStart={(e) => { if (resizeRef.current) { e.preventDefault(); return; } setDragColIdx(i); }}
                                            onDragOver={(e) => { e.preventDefault(); setDragOverColIdx(i); }}
                                            onDrop={() => { reorderColumns(dragColIdx, i); setDragColIdx(null); setDragOverColIdx(null); }}
                                            onDragEnd={() => { setDragColIdx(null); setDragOverColIdx(null); }}
                                            className={cn(
                                                col.id === 'company' && 'col-name',
                                                isDragging && 'opacity-45',
                                                isDragOver && 'bg-accent text-accent-foreground',
                                                'group/col relative h-auto cursor-grab select-none active:cursor-grabbing'
                                            )}
                                        >
                                            <span className="inline-block align-middle">
                                                {k ? (
                                                    <button type="button" onClick={() => onSort(k)} className="inline-flex items-center gap-1 bg-transparent p-0 font-[inherit] text-[inherit] uppercase border-none text-left">
                                                        <span>{col.label}</span>
                                                        {sortKey === k
                                                            ? (sortDir === 'asc' ? <ArrowUp className="size-3 text-muted-foreground" /> : <ArrowDown className="size-3 text-muted-foreground" />)
                                                            : <ChevronsUpDown className="size-3 opacity-40" />}
                                                    </button>
                                                ) : (
                                                    <span className="uppercase">{col.label}</span>
                                                )}
                                            </span>
                                            <ColumnResizeGrip onMouseDown={(e) => startResize(e, col.id)} active={resizingId === col.id} />
                                        </th>
                                    );
                                })}
                            </tr>
                        </thead>
                        <tbody>
                            {rows.length === 0 ? (
                                <tr>
                                    <td colSpan={visibleCols.length} className="py-8 !text-center">No quotations awaiting feedback.</td>
                                </tr>
                            ) : (
                                rows.map((q) => (
                                    <tr
                                        key={q.id}
                                        onClick={() => router.visit(route('quotations.feedback.show', q.id))}
                                        className="cursor-pointer"
                                    >
                                        {visibleCols.map((col) => {
                                            const cellClass = cn(
                                                col.id === 'company' && 'col-name',
                                                col.id === 'productList' && '!whitespace-normal min-w-70 max-w-105 align-top text-foreground'
                                            );
                                            return (
                                                <td key={col.id} className={cellClass}>
                                                    {renderCell(q, col.id)}
                                                </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={[5, 10, 15, 20]}
                  total={quotations.total}
                  itemLabel="quotations"
              />
            </article>

            <CustomizeColumnsModal open={customizeOpen} onClose={() => setCustomizeOpen(false)} groups={COLUMN_GROUPS} definitions={COLUMN_DEFS} state={columnState} onApply={handleApplyColumns} onReset={handleResetColumns} />
        </section>
    );
}

QuotationFeedbackList.layout = [AppLayout];
