import { router, usePage } from '@inertiajs/react';
import type { ColDef } from 'ag-grid-community';
import { AgGridReact } from 'ag-grid-react';
import type { CustomCellRendererProps } from 'ag-grid-react';
import { CloudUpload, Plus } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { CatalogStatusBadge } from '@/components/shared/badges';
import { PageHeader } from '@/components/shared/page-header';
import { Pagination } from '@/components/shared/pagination';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { astaraGridTheme } from '@/lib/ag-grid-theme';
import { brandLabel, formatDateTime, updateQuery } from '@/lib/catalog';
import {
    publishAll,
    show as pricelistShow,
    store as pricelistStore,
} from '@/routes/catalog/pricelists';
import type {
    CatalogPricelistPublishReport,
    CatalogPricelistRow,
    CatalogPricelistsIndexProps,
} from '@/types/catalog';

/** P009 bulk-publish feedback; count comes from the publish_report flash. */
function announcePublishReport(
    report: CatalogPricelistPublishReport | null | undefined,
): void {
    if (report && typeof report.published === 'number') {
        toast.success(
            `Publish all — ${report.published} ${
                report.published === 1 ? 'pricelist' : 'pricelists'
            } published`,
        );

        return;
    }

    toast.success('Publish all finished');
}

const PublishReportBox = ({
    report,
}: {
    report: CatalogPricelistPublishReport;
}) => (
    <div className="mb-4 rounded-xl border border-green-200 bg-green-50/60 px-4 py-3">
        <p className="text-[11px] font-bold text-green-800">
            Publish all applied — {report.published}{' '}
            {report.published === 1 ? 'pricelist' : 'pricelists'} in scope
            published (Draft → Current, Current republished).
        </p>
    </div>
);

const KeyCell = ({ value }: { value: string | null }) => (
    <div className="flex h-full items-center font-mono text-[10px] text-gray-500">
        {value ?? '—'}
    </div>
);

const BrandCell = ({ data }: CustomCellRendererProps<CatalogPricelistRow>) => (
    <div className="flex h-full items-center text-[11px] font-bold text-astara-purple uppercase">
        {data?.brand_code}
    </div>
);

const StatusCell = ({ data }: CustomCellRendererProps<CatalogPricelistRow>) => (
    <div className="flex h-full items-center">
        {data && <CatalogStatusBadge status={data.status} />}
    </div>
);

const VersionCell = ({
    data,
}: CustomCellRendererProps<CatalogPricelistRow>) => (
    <div className="flex h-full items-center font-mono text-[11px] text-gray-600">
        v{data?.version_no ?? 0}
    </div>
);

const UpdatedCell = ({
    data,
}: CustomCellRendererProps<CatalogPricelistRow>) => (
    <div className="flex h-full items-center text-[10px] text-gray-500">
        {formatDateTime(data?.updated_at ?? null)}
    </div>
);

export function PricelistsIndexView({
    pricelists,
    filters,
    publish_report,
}: CatalogPricelistsIndexProps) {
    const [modelYearId, setModelYearId] = useState('');
    const [bodyTypeId, setBodyTypeId] = useState('');
    const [publishingAll, setPublishingAll] = useState(false);
    const { props } = usePage();
    const canEdit = props.auth.can.edit_catalog;

    useEffect(() => {
        if (publish_report) {
            announcePublishReport(publish_report);
        }
    }, [publish_report]);

    const runPublishAll = () => {
        setPublishingAll(true);
        router.post(
            publishAll({
                query: filters.brand ? { brand: filters.brand } : undefined,
            }) as never,
            {},
            {
                preserveScroll: true,
                onSuccess: (page) =>
                    announcePublishReport(
                        (
                            page.props as {
                                publish_report?: CatalogPricelistPublishReport | null;
                            }
                        ).publish_report,
                    ),
                onFinish: () => setPublishingAll(false),
            },
        );
    };

    const [columnDefs] = useState<ColDef<CatalogPricelistRow>[]>(() => [
        {
            colId: 'brand',
            headerName: 'Brand',
            field: 'brand_code',
            width: 110,
            cellRenderer: BrandCell,
        },
        {
            colId: 'model',
            headerName: 'Model',
            field: 'model_key',
            width: 140,
            cellRenderer: KeyCell,
        },
        {
            colId: 'year',
            headerName: 'Year',
            field: 'year_key',
            width: 90,
            cellRenderer: KeyCell,
        },
        {
            colId: 'type',
            headerName: 'Type',
            field: 'body_key',
            width: 90,
            cellRenderer: KeyCell,
        },
        {
            colId: 'status',
            headerName: 'Status',
            field: 'status',
            width: 110,
            cellRenderer: StatusCell,
        },
        {
            colId: 'version',
            headerName: 'Version',
            field: 'version_no',
            width: 80,
            cellRenderer: VersionCell,
        },
        {
            colId: 'published',
            headerName: 'Published',
            field: 'published_at',
            width: 160,
            cellRenderer: UpdatedCell,
        },
        {
            colId: 'updated',
            headerName: 'Updated',
            field: 'updated_at',
            flex: 1,
            cellRenderer: UpdatedCell,
        },
    ]);

    return (
        <div className="flex flex-1 flex-col overflow-hidden">
            <PageHeader
                title="Pricelists"
                subtitle="Publishable price documents per brand / model year / type"
            />

            <div className="custom-scroll flex-1 overflow-y-auto p-4 md:p-6">
                {publish_report && <PublishReportBox report={publish_report} />}
                <div className="mb-4 flex flex-col gap-3">
                    <div className="flex flex-wrap items-center gap-3">
                        {canEdit && (
                            <div className="flex flex-wrap items-end gap-2">
                                <div>
                                    <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                                        Model year ID
                                    </label>
                                    <Input
                                        value={modelYearId}
                                        onChange={(event) =>
                                            setModelYearId(event.target.value)
                                        }
                                        className="h-8 w-28 bg-white text-xs"
                                        placeholder="e.g. 1"
                                    />
                                </div>
                                <div>
                                    <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                                        Body type ID
                                    </label>
                                    <Input
                                        value={bodyTypeId}
                                        onChange={(event) =>
                                            setBodyTypeId(event.target.value)
                                        }
                                        className="h-8 w-28 bg-white text-xs"
                                        placeholder="e.g. 3"
                                    />
                                </div>
                                <Button
                                    size="sm"
                                    onClick={() =>
                                        router.post(
                                            pricelistStore() as never,
                                            {
                                                model_year_id:
                                                    Number(modelYearId),
                                                body_type_id:
                                                    Number(bodyTypeId),
                                            },
                                            { preserveScroll: true },
                                        )
                                    }
                                    disabled={
                                        modelYearId === '' || bodyTypeId === ''
                                    }
                                >
                                    <Plus size={14} />
                                    Create
                                </Button>
                            </div>
                        )}
                        {canEdit && (
                            <Button
                                size="sm"
                                variant="outline"
                                onClick={runPublishAll}
                                disabled={publishingAll}
                            >
                                <CloudUpload size={14} />
                                Publish all
                                {filters.brand &&
                                    ` (${brandLabel(filters.brand)})`}
                            </Button>
                        )}
                        <Select
                            value={filters.status ?? 'all'}
                            onValueChange={(value) =>
                                updateQuery({
                                    status: value === 'all' ? null : value,
                                })
                            }
                        >
                            <SelectTrigger
                                size="sm"
                                className="w-40 bg-white text-xs"
                            >
                                <SelectValue placeholder="All statuses" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">
                                    All statuses
                                </SelectItem>
                                {['Draft', 'Current', 'Past', 'Archived'].map(
                                    (status) => (
                                        <SelectItem key={status} value={status}>
                                            {status}
                                        </SelectItem>
                                    ),
                                )}
                            </SelectContent>
                        </Select>
                    </div>
                </div>

                <div className="flex flex-col overflow-hidden rounded-xl border border-[rgba(30,25,50,0.06)] bg-white shadow-[0_2px_8px_rgba(30,25,50,0.04)]">
                    <div className="h-[480px]">
                        <AgGridReact<CatalogPricelistRow>
                            theme={astaraGridTheme}
                            rowData={pricelists.data}
                            columnDefs={columnDefs}
                            getRowId={(params) => String(params.data.id)}
                            onRowClicked={(event) => {
                                if (event.data) {
                                    router.visit(
                                        pricelistShow({
                                            pricelist: event.data.id,
                                        }),
                                    );
                                }
                            }}
                            rowClass="cursor-pointer"
                            rowHeight={38}
                            headerHeight={36}
                            suppressCellFocus
                            defaultColDef={{ resizable: true }}
                        />
                    </div>
                    <Pagination
                        links={pricelists.links}
                        meta={pricelists.meta}
                    />
                </div>
            </div>
        </div>
    );
}
