import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { QuotationListPage } from '@/Components/MenuQuotations/QuotationListPage/QuotationListPage';
import { ExportButton } from '@/lib/excel/ExportButton';
import { INVOICE_COLUMNS, SCOPE_META, invoiceListPills, renderInvoiceCell } from '@/Components/MenuCompanies/GenerateCompanyRebate/invoiceListConfig';

/**
 * The single Generate Company Rebate List page — serves all nine legacy list menus of
 * sub-group #400 through the `scope` prop (view-request / view-creator / view-sm / view-all /
 * view-all-readonly / approval-finance / approval-sm / approval-ceo / bill). Reuses the shared
 * <QuotationListPage> shell; rows link to the matching detail page via `rowHref`.
 *
 * There is no Create button here: rebate invoices are produced by the Generate screen
 * (legacy #404), which is a later phase.
 */

/** Detail page route per scope. */
const DETAIL_ROUTES = {
    'view-request': 'generate-company-rebates.view-request.show',
    'view-creator': 'generate-company-rebates.view-creator.show',
    'view-sm': 'generate-company-rebates.view-sm.show',
    'view-all': 'generate-company-rebates.view-all.show',
    'view-all-readonly': 'generate-company-rebates.view-all-readonly.show',
    'approval-finance': 'generate-company-rebates.approval-finance.show',
    'approval-sm': 'generate-company-rebates.approval-sm.show',
    'approval-ceo': 'generate-company-rebates.approval-ceo.show',
    'bill': 'generate-company-rebates.bill.show',
};

export default function GenerateCompanyRebateList({ invoices, scope, filters, filterOptions }) {

    // Products column: ONE title, TWO renderings, chosen under that column's own row in the ⚙
    // modal (user 2026-08-24: "1 title tapi bisa 2 pilihan di settings … kayak yang di view
    // sample order"). Mirrors /sample-orders' Sample List mode — same wording on the buttons,
    // same localStorage-per-device persistence as every other column preference.
    const [productsMode, setProductsMode] = useState(() => {
        try { return localStorage.getItem('generateRebateProductsMode_v1') === 'full' ? 'full' : 'compact'; }
        catch { return 'compact'; }
    });
    const applyProductsMode = (m) => {
        setProductsMode(m);
        try { localStorage.setItem('generateRebateProductsMode_v1', m); } catch { /* private mode */ }
    };
    const meta = SCOPE_META[scope] ?? { title: 'Generate Company Rebate', crumb: 'List' };
    const detailRoute = DETAIL_ROUTES[scope];
    // Guard the row link: the detail routes land in a later step of this phase, and a rowHref
    // pointing at an unregistered route name throws inside Ziggy rather than degrading.
    const hasDetailRoute = detailRoute && typeof route === 'function' && route().has(detailRoute);

    return (
        <QuotationListPage
            title={meta.title}
            breadcrumb={[{ label: 'Company Rebate' }, { label: 'Generate Company Rebate' }, { label: meta.crumb }]}
            headerActions={scope === 'view-all' ? (
                // Legacy's "Export Billed to Excel" — BILLED invoices only, narrowed by the
                // screen's Tanggal range. Built in a Web Worker from the shared spec registry.
                <ExportButton
                    specKey="companyRebateRekapExport"
                    url={route('generate-company-rebates.export.rekap')}
                    params={{ date_from: filters?.date_from || '', date_to: filters?.date_to || '' }}
                    label="Export Billed to Excel"
                />
            ) : null}
            routeName={`generate-company-rebates.${scope}`}
            paginator={invoices}
            dataProp="invoices"
            filters={filters}
            columns={INVOICE_COLUMNS}
            storageKey={`generateCompanyRebateListColumns_${scope}_v1`}
            renderCell={(row, colId, ctx) => renderInvoiceCell(row, colId, { ...ctx, productsMode })}
            widthOverride={(id) => (id === 'products' && productsMode === 'full' ? 300 : null)}
            renderColumnOption={(def) => def.id !== 'products' ? null : (
                <div className="flex items-center gap-1.5 rounded-md bg-secondary/50 p-1">
                    {[['compact', 'Compact (hover)'], ['full', 'Show all items']].map(([m, label]) => (
                        <button key={m} type="button" onClick={() => applyProductsMode(m)} aria-pressed={productsMode === m}
                            className={`flex-1 rounded px-2 py-1 text-[11px] font-bold transition-colors ${productsMode === m ? 'bg-card text-primary shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}>
                            {label}
                        </button>
                    ))}
                </div>
            )}
            rowHref={hasDetailRoute ? (r) => route(detailRoute, { invoice: r.id }) : undefined}
            pills={invoiceListPills(filterOptions, scope)}
            emptyText="No generated company rebates found."
            searchPlaceholder="Search ID / company..."
            searchAriaLabel="Search generated company rebates"
            pageSizeOptions={[10, 20, 50, 100]}
        />
    );
}

GenerateCompanyRebateList.layout = [AppLayout];
