import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { CreateActionButton } from '@/Components/Table/CreateActionButton';
import { QuotationListPage } from '@/Components/MenuQuotations/QuotationListPage/QuotationListPage';
import { REBATE_COLUMNS, SCOPE_META, rebateListPills, renderRebateCell } from '@/Components/MenuCompanies/CompanyRebate/rebateListConfig';

/**
 * The single Company Rebate List page — serves all eight legacy list menus through the
 * `scope` prop (view-request / view-request-sm / view-all / view-all-readonly /
 * approval-sm / approval-ceo / cancel-approval-sm / cancel-approval-ceo). Reuses the
 * shared <QuotationListPage> shell. Rows link to the corresponding detail page via
 * `rowHref`. View All tints every row by validity (legacy: Expired red / On Going green).
 */

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

export default function CompanyRebateList({ rebates, scope, filters, filterOptions, canCreate = false }) {

    // 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('companyRebateProductsMode_v1') === 'full' ? 'full' : 'compact'; }
        catch { return 'compact'; }
    });
    const applyProductsMode = (m) => {
        setProductsMode(m);
        try { localStorage.setItem('companyRebateProductsMode_v1', m); } catch { /* private mode */ }
    };
    const meta = SCOPE_META[scope] ?? { title: 'Company Rebate', crumb: 'List' };
    const detailRoute = DETAIL_ROUTES[scope];

    return (
        <QuotationListPage
            title={meta.title}
            breadcrumb={[{ label: 'Company Rebate' }, { label: meta.crumb }]}
            headerActions={(
                <CreateActionButton canCreate={canCreate} label="New Rebate" href={route('company-rebates.create')} />
            )}
            routeName={`company-rebates.${scope}`}
            paginator={rebates}
            dataProp="rebates"
            filters={filters}
            columns={REBATE_COLUMNS}
            storageKey={`companyRebateListColumns_${scope}_v1`}
            renderCell={(row, colId, ctx) => renderRebateCell(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={detailRoute ? (r) => route(detailRoute, { rebate: r.id }) : undefined}
            rowClass={meta.expiredTint ? (r) => (
                r.expired === true
                    ? '[&_td]:text-danger! [&_td_*]:text-danger!'
                    : r.expired === false
                        ? '[&_td]:text-success! [&_td_*]:text-success!'
                        : null
            ) : null}
            pills={rebateListPills(filterOptions, scope)}
            emptyText="No company rebates found."
            searchPlaceholder="Search ID / company..."
            searchAriaLabel="Search company rebates"
            pageSizeOptions={[10, 20, 50, 100]}
        />
    );
}

CompanyRebateList.layout = [AppLayout];
