import type { ColDef } from 'ag-grid-community';
import { AgGridReact } from 'ag-grid-react';
import type { CustomCellRendererProps } from 'ag-grid-react';
import { History, Loader2 } from 'lucide-react';
import { useState } from 'react';
import { EmptyState } from '@/components/shared/empty-state';
import { PageHeader } from '@/components/shared/page-header';
import { Pagination } from '@/components/shared/pagination';
import { astaraGridTheme } from '@/lib/ag-grid-theme';
import { formatCount, formatDateTime, formatDuration } from '@/lib/catalog';
import { cn } from '@/lib/utils';
import type {
    CatalogImportsIndexProps,
    ImportRun,
    ImportRunStatus,
} from '@/types/catalog';

const STATUS_STYLES: Record<ImportRunStatus, string> = {
    running: 'bg-orange-50 text-amber-700',
    completed: 'bg-green-50 text-green-700',
    failed: 'bg-red-50 text-red-700',
};

const SUMMARY_ROWS = [
    { key: 'models', label: 'Models' },
    { key: 'model_years', label: 'Model years' },
    { key: 'body_types', label: 'Body types' },
    { key: 'engines', label: 'Engines' },
    { key: 'trims', label: 'Trims' },
    { key: 'variants', label: 'Variants' },
    { key: 'entity_features', label: 'Feature rows' },
    { key: 'entity_data_values', label: 'Data values' },
] as const;

const StatusCell = ({ data }: CustomCellRendererProps<ImportRun>) => (
    <div className="flex h-full items-center gap-1.5">
        <span
            className={cn(
                'inline-flex h-[18px] items-center rounded px-2 text-[9px] leading-none font-bold uppercase',
                data ? STATUS_STYLES[data.status] : '',
            )}
        >
            {data?.status}
        </span>
        {data?.status === 'running' && (
            <Loader2 size={12} className="animate-spin text-amber-700" />
        )}
    </div>
);

const NotesCell = ({ data }: CustomCellRendererProps<ImportRun>) => (
    <div className="flex h-full items-center overflow-hidden">
        <span className="truncate text-[10px] text-gray-500 italic">
            {data?.notes ?? '—'}
        </span>
    </div>
);

const VersionCell = ({ data }: CustomCellRendererProps<ImportRun>) => (
    <div className="flex h-full items-center font-mono text-[11px] text-gray-500">
        {data?.api_version ?? '—'}
    </div>
);

const IdCell = ({ data }: CustomCellRendererProps<ImportRun>) => (
    <div className="flex h-full items-center font-mono text-[11px] font-bold text-astara-purple">
        #{data?.id}
    </div>
);

const DateCell = ({ value }: { value: string | null }) => (
    <div className="flex h-full items-center text-[10px] text-gray-500">
        {formatDateTime(value)}
    </div>
);

const DurationCell = ({ data }: CustomCellRendererProps<ImportRun>) => (
    <div className="flex h-full items-center justify-end text-[10px] font-semibold text-gray-500">
        {formatDuration(data?.duration_seconds ?? null)}
    </div>
);

export function ImportsView({
    imports,
    summary,
}: {
    imports: CatalogImportsIndexProps['imports'];
    summary: Record<string, number>;
}) {
    const [columnDefs] = useState<ColDef<ImportRun>[]>([
        {
            colId: 'id',
            headerName: 'Run',
            field: 'id',
            width: 90,
            cellRenderer: IdCell,
        },
        {
            colId: 'api_version',
            headerName: 'API version',
            field: 'api_version',
            width: 120,
            cellRenderer: VersionCell,
        },
        {
            colId: 'status',
            headerName: 'Status',
            field: 'status',
            width: 130,
            cellRenderer: StatusCell,
        },
        {
            colId: 'started_at',
            headerName: 'Started',
            field: 'started_at',
            width: 170,
            cellRenderer: (params: CustomCellRendererProps<ImportRun>) => (
                <DateCell value={params.data?.started_at ?? null} />
            ),
        },
        {
            colId: 'finished_at',
            headerName: 'Finished',
            field: 'finished_at',
            width: 170,
            cellRenderer: (params: CustomCellRendererProps<ImportRun>) => (
                <DateCell value={params.data?.finished_at ?? null} />
            ),
        },
        {
            colId: 'duration_seconds',
            headerName: 'Duration',
            field: 'duration_seconds',
            width: 110,
            cellRenderer: DurationCell,
        },
        {
            colId: 'notes',
            headerName: 'Notes',
            field: 'notes',
            flex: 2,
            minWidth: 260,
            cellRenderer: NotesCell,
        },
    ]);

    return (
        <div className="custom-scroll flex-1 overflow-y-auto">
            <PageHeader
                title="Import Status"
                subtitle="Provenance & integrity — pcm_imports runs"
            />

            <div className="p-4 md:p-6">
                <div className="mb-4 flex flex-wrap items-center gap-1.5">
                    <span className="mr-1 text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                        Catalog totals
                    </span>
                    {SUMMARY_ROWS.map((row) => (
                        <span
                            key={row.key}
                            className="inline-flex items-center gap-1.5 rounded bg-slate-100 px-2 py-1 text-[10px] font-bold tracking-wider text-slate-600 uppercase"
                        >
                            {formatCount(summary[row.key] ?? 0)}
                            <span className="font-semibold text-gray-400">
                                {row.label}
                            </span>
                        </span>
                    ))}
                </div>

                {imports.meta.total === 0 ? (
                    <div className="rounded-xl border border-[rgba(30,25,50,0.06)] bg-white shadow-[0_2px_8px_rgba(30,25,50,0.04)]">
                        <EmptyState
                            icon={History}
                            title="No import runs yet — the catalog has not been loaded"
                            description="Once the first PCM import runs, its audit trail (row counts, validation notes) appears here."
                        />
                    </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-[520px]">
                            <AgGridReact<ImportRun>
                                theme={astaraGridTheme}
                                rowData={imports.data}
                                columnDefs={columnDefs}
                                getRowId={(params) => String(params.data.id)}
                                animateRows
                                rowHeight={40}
                                headerHeight={36}
                                suppressCellFocus
                                defaultColDef={{ resizable: true }}
                            />
                        </div>
                        <Pagination links={imports.links} meta={imports.meta} />
                    </div>
                )}
            </div>
        </div>
    );
}
