import type { Column } from './components';
import type { ConfirmState } from './ConfirmDialog';
import type { Item } from './shared';
import { useState } from 'react';
import { Filter, MoreHorizontal, Package, Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { EmptyState, ErrorState, Pagination, SearchBox, SectionShell, SimpleTable } from './components';
import { ConfirmDialog } from './ConfirmDialog';
import { formatDate, formatMoney, parseMoneyMinor } from './format';
import { PAGE_SIZE } from './shared';
import { useListFilters } from './useInvoicesSection';
import { useCurrency, useLookups, useResourceList, useResourceMutations } from './useInvoiceShelfData';

// Items — the reusable line-item catalogue. The shortest screen here, and the only list with no detail pane:
// an item is four fields, so clicking one opens the editor directly rather than a preview of itself.

type Props = { onEdit: (id: number | 'new') => void };

export const ItemsListView = ({ onEdit }: Props) => {
  const { filters, patch, setPage, clearFilters } = useListFilters();
  const currency = useCurrency();
  const { units } = useLookups();
  const [showFilters, setShowFilters] = useState(false);
  const [priceInput, setPriceInput] = useState('');
  const [selection, setSelection] = useState<Set<number>>(new Set());
  const [confirm, setConfirm] = useState<ConfirmState>(null);

  const { rows, meta, isLoading, error } = useResourceList<Item>('items', {
    page: filters.page,
    limit: PAGE_SIZE,
    search: filters.search || undefined,
    unit_id: filters.customerId || undefined,
    // Upstream matches price EXACTLY, in minor units — it is a lookup, not a range. `1000` finds items
    // priced at 10.00 and nothing else.
    price: filters.status || undefined,
    orderByField: 'created_at',
    orderBy: 'desc',
  });

  const { remove, removeMany } = useResourceMutations('items');

  const toggleRow = (id: number) =>
    setSelection((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });

  const allChecked = rows.length > 0 && rows.every((r) => selection.has(r.id));

  const columns: Column<Item>[] = [
    {
      key: 'check',
      label: '',
      width: '36px',
      render: (row) => (
        <span onClick={(e) => e.stopPropagation()} className="flex items-center">
          <Checkbox checked={selection.has(row.id)} onCheckedChange={() => toggleRow(row.id)} />
        </span>
      ),
    },
    {
      key: 'name',
      label: 'Name',
      width: 'minmax(150px, 2fr)',
      render: (row) => (
        <div className="min-w-0">
          <div className="truncate font-medium">{row.name}</div>
          {row.description && <div className="truncate text-[10px] text-muted-foreground">{row.description}</div>}
        </div>
      ),
    },
    {
      key: 'unit',
      label: 'Unit',
      width: 'minmax(80px, 0.8fr)',
      render: (row) => row.unit?.name ?? '—',
    },
    {
      key: 'price',
      label: 'Price',
      width: 'minmax(100px, 1fr)',
      align: 'right',
      render: (row) => formatMoney(row.price, currency),
    },
    {
      key: 'created_at',
      label: 'Added',
      width: 'minmax(90px, 0.9fr)',
      render: (row) => formatDate(null, row.formatted_created_at),
    },
  ];

  const rowMenu = (row: Item) => (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="sm" className="h-6 w-6 p-0">
          <MoreHorizontal className="h-3.5 w-3.5" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-44">
        <DropdownMenuItem onSelect={() => onEdit(row.id)}>Edit</DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem
          className="text-red-600"
          onSelect={() =>
            setConfirm({
              title: `Delete ${row.name}?`,
              description:
                'Lines already written from this item stay as they are — an invoice keeps its own copy of the name and price.',
              confirmLabel: 'Delete',
              destructive: true,
              onConfirm: () => remove.mutate(row.id),
            })
          }
        >
          <Trash2 className="mr-2 h-3.5 w-3.5" />
          Delete
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );

  if (error) return <ErrorState error={error} />;

  const applyPrice = () => {
    const trimmed = priceInput.trim();
    patch({ status: trimmed ? String(parseMoneyMinor(trimmed, currency)) : null });
  };

  const toolbar = (
    <>
      <Checkbox
        checked={allChecked}
        onCheckedChange={() => setSelection(allChecked ? new Set() : new Set(rows.map((r) => r.id)))}
      />
      <SearchBox value={filters.search} onChange={(v) => patch({ q: v })} placeholder="Item name…" />
      <Button
        variant={showFilters || filters.isFiltered ? 'secondary' : 'ghost'}
        size="sm"
        className="h-8"
        onClick={() => setShowFilters((v) => !v)}
      >
        <Filter className="mr-1.5 h-3.5 w-3.5" />
        Filter
      </Button>
      <div className="ml-auto flex items-center gap-2">
        {selection.size > 0 && (
          <Button
            variant="ghost"
            size="sm"
            className="h-8 text-red-600"
            onClick={() =>
              setConfirm({
                title: `Delete ${selection.size} items?`,
                description: 'Lines already written from them are unaffected.',
                confirmLabel: 'Delete',
                destructive: true,
                onConfirm: () => {
                  removeMany.mutate([...selection]);
                  setSelection(new Set());
                },
              })
            }
          >
            <Trash2 className="mr-1.5 h-3.5 w-3.5" />
            Delete {selection.size}
          </Button>
        )}
        <Button size="sm" className="h-8" onClick={() => onEdit('new')}>
          <Plus className="mr-1.5 h-3.5 w-3.5" />
          New item
        </Button>
      </div>
    </>
  );

  return (
    <>
      <SectionShell toolbar={toolbar} footer={<Pagination meta={meta} onPage={setPage} />}>
        {showFilters && (
          <div className="flex flex-wrap items-end gap-3 border-b border-border bg-muted/20 px-3 py-2">
            <label className="flex flex-col gap-1 text-[10px] text-muted-foreground">
              Unit
              <select
                value={filters.customerId ?? ''}
                onChange={(e) => patch({ customer: e.target.value || null })}
                className="h-8 rounded-md border border-input bg-background px-2 text-xs"
              >
                <option value="">All</option>
                {units.map((u) => (
                  <option key={u.id} value={u.id}>
                    {u.name}
                  </option>
                ))}
              </select>
            </label>
            <label className="flex flex-col gap-1 text-[10px] text-muted-foreground">
              Exact price
              <Input
                value={priceInput}
                onChange={(e) => setPriceInput(e.target.value)}
                onBlur={applyPrice}
                onKeyDown={(e) => e.key === 'Enter' && applyPrice()}
                placeholder="10.00"
                className="h-8 w-28 text-xs"
              />
            </label>
            {filters.isFiltered && (
              <Button
                variant="ghost"
                size="sm"
                className="h-8"
                onClick={() => {
                  setPriceInput('');
                  clearFilters();
                }}
              >
                Clear
              </Button>
            )}
          </div>
        )}

        <SimpleTable
          rows={rows}
          columns={columns}
          rowKey={(r) => r.id}
          onRowClick={(r) => onEdit(r.id)}
          rowMenu={rowMenu}
          empty={
            isLoading ? (
              <EmptyState icon={Package} title="Loading…" />
            ) : (
              <EmptyState
                icon={Package}
                title={filters.isFiltered ? 'No items match' : 'No items yet'}
                hint={
                  filters.isFiltered
                    ? 'Try clearing the filters.'
                    : 'Items are optional — they just save retyping the same line.'
                }
              />
            )
          }
        />
      </SectionShell>

      <ConfirmDialog state={confirm} onClose={() => setConfirm(null)} />
    </>
  );
};
