import { Link, router } from '@inertiajs/react';
import { Download, ImageIcon, Plus, Upload } from 'lucide-react';
import { BLOCK_META, STRUCTURED_TYPES, type StructuredType } from '@/components/quote/BlockEditors';
import { BlockMenu } from '@/components/quote/LinesEditor';
import { useState } from 'react';
import { CsvImportDialog } from '@/components/CsvImportDialog';
import { PageHeader } from '@/components/PageHeader';
import { Pagination } from '@/components/Pagination';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input, Select } from '@/components/ui/input';
import { Table, Td, Th } from '@/components/ui/table';
import AppLayout from '@/layouts/AppLayout';
import { money } from '@/lib/format';
import type { Paginated } from '@/types';

type Row = {
    id: number; type: 'price' | 'text' | 'image' | StructuredType; image_url?: string | null; code: string | null; heading: string; unit_price_cents: number | null;
    tax_rate_bp: number; subscription: string | null; archived: boolean;
};

export default function ItemsIndex({ items, filters, canEdit, company }: {
    items: Paginated<Row>; filters: { q: string | null; type: string | null; archived: boolean }; canEdit: boolean; company: { id: number; name: string };
}) {
    const [q, setQ] = useState(filters.q ?? '');
    const [importing, setImporting] = useState(false);
    const apply = (patch: Partial<{ q: string; type: string | null; archived: boolean }>) => {
        const next = { q, type: filters.type, archived: filters.archived, ...patch };
        router.get('/items', Object.fromEntries(Object.entries({ q: next.q || null, type: next.type || null, archived: next.archived ? 1 : null }).filter(([, v]) => v)),
            { preserveState: true, replace: true });
    };

    return (
        <AppLayout title="Item library">
            <PageHeader title="Item library" description={`Price items, text, images and proposal blocks for ${company.name}. Add them to quotes with the library search.`}
                actions={<>
                    <Button variant="secondary" asChild><a href="/items/export" data-testid="export-items"><Download className="h-4 w-4" /> Export CSV</a></Button>
                    {canEdit && <Button variant="secondary" onClick={() => setImporting(true)} data-testid="import-items"><Upload className="h-4 w-4" /> Import CSV</Button>}
                    {canEdit && <Button asChild data-testid="new-item"><Link href="/items/create"><Plus className="h-4 w-4" /> Price item</Link></Button>}
                    {canEdit && <Button variant="secondary" asChild><Link href="/items/create?type=text"><Plus className="h-4 w-4" /> Text</Link></Button>}
                    {canEdit && <Button variant="secondary" asChild><Link href="/items/create?type=image" data-testid="new-image-item"><ImageIcon className="h-4 w-4" /> Image</Link></Button>}
                    {canEdit && <BlockMenu below testId="new-block-item" onPick={(t) => router.visit(`/items/create?type=${t}`)} />}
                </>} />
            <CsvImportDialog open={importing} onOpenChange={setImporting} url="/items/import" reload="items"
                title="Import items" description={`Upload a CSV of price or text items for ${company.name} (e.g. Quotient's Price Items or Text Items export).`}
                updateLabel="Update items that already exist (matched by item code)"
                help={<>Recognised columns: Type, Item Code, Heading (or Name), Description, Unit Price, Quantity, Tax Rate (10%, GST, GST Free), Discount %,
                    Cost Price, Markup % or Margin %, Frequency (Weekly / Monthly / Yearly), Every, Term. Other columns are ignored. Up to 1,000 rows per file.{' '}
                    <a href="/items/export" className="link">Export your items</a> to see the format.</>} />
            <Card>
                <form className="flex flex-wrap items-center gap-3 border-b border-line p-4" onSubmit={(e) => { e.preventDefault(); apply({}); }}>
                    <Input aria-label="Search items" placeholder="Search code or heading" value={q} onChange={(e) => setQ(e.target.value)} className="max-w-xs" />
                    <Select aria-label="Item type" value={filters.type ?? ''} onChange={(e) => apply({ type: e.target.value || null })} className="w-auto">
                        <option value="">All types</option>
                        <option value="price">Price items</option>
                        <option value="text">Text items</option>
                        <option value="image">Images</option>
                        {STRUCTURED_TYPES.map((t) => <option key={t} value={t}>{BLOCK_META[t].label}</option>)}
                    </Select>
                    <Button type="submit" variant="secondary">Search</Button>
                    <Checkbox label="Show archived" checked={filters.archived} onChange={(e) => apply({ archived: e.target.checked })} />
                </form>
                <Table data-testid="items-table">
                    <thead><tr><Th>Code</Th><Th>Heading</Th><Th>Type</Th><Th>Tax</Th><Th>Billing</Th><Th className="text-right">Unit price</Th></tr></thead>
                    <tbody>
                        {items.data.map((i) => (
                            <tr key={i.id}>
                                <Td className="whitespace-nowrap font-mono text-xs text-ink-muted">{i.code ?? '—'}</Td>
                                <Td className="font-medium">
                                    {i.image_url && <img src={i.image_url} alt="" className="mr-2 inline-block h-8 w-8 rounded object-cover align-middle" />}
                                    <Link href={`/items/${i.id}/edit`} className="link">{i.heading}</Link>
                                    {i.archived && <Badge className="ml-2 bg-stone-100 text-stone-700">Archived</Badge>}
                                </Td>
                                <Td>{i.type === 'text' ? 'Text' : i.type === 'price' ? 'Price' : i.type === 'image' ? 'Image' : BLOCK_META[i.type].label}</Td>
                                <Td className="whitespace-nowrap">{i.type !== 'price' ? '—' : i.tax_rate_bp === 0 ? 'GST-free' : `${i.tax_rate_bp / 100}%`}</Td>
                                <Td className="whitespace-nowrap">{i.type !== 'price' ? '—' : i.subscription ?? 'One-off'}</Td>
                                <Td className="text-right tabular-nums">{i.type !== 'price' ? '—' : money(i.unit_price_cents)}</Td>
                            </tr>
                        ))}
                        {items.data.length === 0 && (
                            <tr><Td colSpan={6} className="py-10 text-center text-ink-muted">
                                {filters.q ? 'No items match your search.' : filters.archived ? 'No archived items.' : 'No items yet.'}
                                {canEdit && !filters.q && !filters.archived && <> <Link href="/items/create" className="link">Add your first item</Link>.</>}
                            </Td></tr>
                        )}
                    </tbody>
                </Table>
                <Pagination page={items} />
            </Card>
        </AppLayout>
    );
}
