import type { Column } from './components';
import type { ConfirmState } from './ConfirmDialog';
import type { SendTarget } from './SendDocumentDialog';
import type { Payment } from './shared';
import { useState } from 'react';
import { Filter, MoreHorizontal, Plus, Send, Trash2, Wallet } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
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 { SendDocumentDialog } from './SendDocumentDialog';
import { PdfPane } from './PdfPane';
import { formatDate, formatMoney } from './format';
import { PAGE_SIZE } from './shared';
import { useListFilters } from './useInvoicesSection';
import { useCurrency, useLookups, useResourceList, useResourceMutations } from './useInvoiceShelfData';

// Payments — upstream's PaymentIndexView. A payment is a receipt against an invoice, so the interesting
// columns are which invoice and by what method; the PDF is the receipt itself.
//
// There is no status here and so no tabs: a payment either exists or it does not.

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

export const PaymentsListView = ({ onEdit }: Props) => {
  const { filters, patch, select, setPage, clearFilters } = useListFilters();
  const currency = useCurrency();
  const { customers, paymentMethods } = useLookups();
  const [showFilters, setShowFilters] = useState(false);
  const [selection, setSelection] = useState<Set<number>>(new Set());
  const [confirm, setConfirm] = useState<ConfirmState>(null);
  const [sendTarget, setSendTarget] = useState<SendTarget | null>(null);

  const { rows, meta, isLoading, error } = useResourceList<Payment>('payments', {
    page: filters.page,
    limit: PAGE_SIZE,
    payment_number: filters.search || undefined,
    customer_id: filters.customerId || undefined,
    payment_method_id: filters.status || undefined,
    orderByField: 'created_at',
    orderBy: 'desc',
  });

  const { remove, removeMany } = useResourceMutations('payments');
  const selected = rows.find((r) => r.id === filters.selected) ?? null;

  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<Payment>[] = [
    {
      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: 'payment_date',
      label: 'Date',
      width: 'minmax(90px, 0.8fr)',
      render: (row) => formatDate(row.payment_date, row.formatted_payment_date),
    },
    {
      key: 'payment_number',
      label: 'Number',
      width: 'minmax(100px, 0.9fr)',
      render: (row) => <span className="font-medium">{row.payment_number}</span>,
    },
    {
      key: 'name',
      label: 'Customer',
      width: 'minmax(120px, 1.3fr)',
      render: (row) => <span className="truncate">{row.customer?.name ?? '—'}</span>,
    },
    {
      key: 'payment_mode',
      label: 'Mode',
      width: 'minmax(90px, 0.9fr)',
      render: (row) => row.payment_method?.name ?? '—',
    },
    {
      key: 'invoice_number',
      label: 'Invoice',
      width: 'minmax(90px, 0.9fr)',
      render: (row) => row.invoice?.invoice_number ?? '—',
    },
    {
      key: 'amount',
      label: 'Amount',
      width: 'minmax(100px, 1fr)',
      align: 'right',
      render: (row) => formatMoney(row.amount, currency),
    },
  ];

  const rowMenu = (row: Payment) => (
    <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-52">
        <DropdownMenuItem onSelect={() => onEdit(row.id)}>Edit</DropdownMenuItem>
        <DropdownMenuItem onSelect={() => select(row.id)}>View receipt</DropdownMenuItem>
        <DropdownMenuItem
          onSelect={() =>
            setSendTarget({
              resource: 'payments',
              id: row.id,
              number: row.payment_number,
              customerName: row.customer?.name ?? '',
              customerEmail: row.customer?.email ?? null,
            })
          }
        >
          <Send className="mr-2 h-3.5 w-3.5" />
          Send receipt
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem
          className="text-red-600"
          onSelect={() =>
            setConfirm({
              title: `Delete payment ${row.payment_number}?`,
              description:
                'The amount goes back onto the linked invoice as due. This does not refund anything — it only removes the record.',
              confirmLabel: 'Delete',
              destructive: true,
              onConfirm: () => {
                remove.mutate(row.id);
                if (filters.selected === row.id) select(null);
              },
            })
          }
        >
          <Trash2 className="mr-2 h-3.5 w-3.5" />
          Delete
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );

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

  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="Payment number…" />
      <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} payments?`,
                description: 'Their amounts go back onto the linked invoices as due.',
                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 payment
        </Button>
      </div>
    </>
  );

  return (
    <>
      <div className="flex h-full min-h-0">
        <div className="min-w-0 flex-1">
          <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">
                  Customer
                  <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>
                    {customers.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </label>
                <label className="flex flex-col gap-1 text-[10px] text-muted-foreground">
                  Payment mode
                  {/* Reuses the `status` slot in the query string — one filter key per list, and payments
                      have no status of their own to compete for it. */}
                  <select
                    value={filters.status ?? ''}
                    onChange={(e) => patch({ status: e.target.value || null })}
                    className="h-8 rounded-md border border-input bg-background px-2 text-xs"
                  >
                    <option value="">All</option>
                    {paymentMethods.map((m) => (
                      <option key={m.id} value={m.id}>
                        {m.name}
                      </option>
                    ))}
                  </select>
                </label>
                {filters.isFiltered && (
                  <Button variant="ghost" size="sm" className="h-8" onClick={clearFilters}>
                    Clear
                  </Button>
                )}
              </div>
            )}

            <SimpleTable
              rows={rows}
              columns={columns}
              rowKey={(r) => r.id}
              selectedKey={filters.selected}
              onRowClick={(r) => select(r.id === filters.selected ? null : r.id)}
              rowMenu={rowMenu}
              empty={
                isLoading ? (
                  <EmptyState icon={Wallet} title="Loading…" />
                ) : (
                  <EmptyState
                    icon={Wallet}
                    title={filters.isFiltered ? 'No payments match' : 'No payments yet'}
                    hint={
                      filters.isFiltered
                        ? 'Try clearing the filters.'
                        : 'Record one against a sent invoice to mark it paid.'
                    }
                  />
                )
              }
            />
          </SectionShell>
        </div>

        {selected && (
          <div className="hidden w-[46%] min-w-[380px] shrink-0 lg:block">
            <PdfPane
              resource="payments"
              id={selected.id}
              title={`Payment ${selected.payment_number}`}
              subtitle={selected.customer?.name}
              filename={`payment-${selected.payment_number}`}
              onClose={() => select(null)}
            />
          </div>
        )}
      </div>

      <ConfirmDialog state={confirm} onClose={() => setConfirm(null)} />
      <SendDocumentDialog target={sendTarget} currency={currency} onClose={() => setSendTarget(null)} />
    </>
  );
};
