import { useState } from 'react';
import { Badge } from '@rutatiina/ui/components/ui/badge';
import { Button } from '@rutatiina/ui/components/ui/button';
import {
  Card,
  CardDescription,
  CardHeader,
  CardHeading,
  CardTable,
  CardTitle,
} from '@rutatiina/ui/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@rutatiina/ui/components/ui/table';
import Link from '@rutatiina/ui/components/common/link';
import { formatDateTime } from '@rutatiina/ui/lib/helpers';
import { useTrans } from '@rutatiina/ui/lib/translations';

export type WorkItem = {
  category: string;
  kind: string;
  ref: string;
  who: string | null;
  amount: string | null;
  since: string | null;
  href: string;
  count: number;
};

export const CATEGORY_LABELS: Record<string, string> = {
  loans: 'Loans',
  savings: 'Savings',
  shares: 'Shares',
  investments: 'Investments',
  members: 'Members',
  cash: 'Cash',
  accounting: 'Accounting',
};

/** Everything waiting on the signed-in person, filtered by the module it belongs to. */
export function WorkQueueTable({ items }: { items: WorkItem[] }) {
  const __ = useTrans();
  const [category, setCategory] = useState('all');
  const categories = [
    'all',
    ...Object.keys(CATEGORY_LABELS).filter((c) =>
      items.some((i) => i.category === c),
    ),
  ];
  const rows = items.filter(
    (item) => category === 'all' || item.category === category,
  );
  const total = (list: WorkItem[]) => list.reduce((n, i) => n + i.count, 0);

  return (
    <Card className="h-full min-w-0">
      <CardHeader className="py-4">
        <CardHeading>
          <CardTitle>{__('Waiting on you')}</CardTitle>
          <CardDescription>
            {__(
              'Approvals, reviews, cash and journals that need a second person. Work you prepared is not listed.',
            )}
          </CardDescription>
        </CardHeading>
      </CardHeader>
      <div
        role="group"
        aria-label={__('Filter work queue')}
        className="flex flex-wrap gap-1.5 px-5 pt-4 pb-3"
      >
        {categories.map((c) => (
          <Button
            key={c}
            size="sm"
            shape="circle"
            variant={category === c ? 'mono' : 'outline'}
            aria-pressed={category === c}
            onClick={() => setCategory(c)}
          >
            {c === 'all' ? __('All') : __(CATEGORY_LABELS[c])}
            <span className="opacity-70">
              {total(
                c === 'all' ? items : items.filter((i) => i.category === c),
              )}
            </span>
          </Button>
        ))}
      </div>
      <CardTable>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{__('What')}</TableHead>
              <TableHead>{__('Reference')}</TableHead>
              <TableHead>{__('Member / source')}</TableHead>
              <TableHead className="text-end">{__('Amount (UGX)')}</TableHead>
              <TableHead>{__('Waiting since')}</TableHead>
              <TableHead>
                <span className="sr-only">{__('Open')}</span>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.map((row, index) => (
              <TableRow key={`${row.category}-${row.kind}-${row.ref}-${index}`}>
                <TableCell className="py-3">
                  <div className="text-mono">{row.kind}</div>
                  <Badge
                    variant="secondary"
                    appearance="light"
                    shape="circle"
                    className="mt-1 whitespace-nowrap"
                  >
                    {__(CATEGORY_LABELS[row.category] ?? row.category)}
                    {row.count > 1 ? ` · ${row.count}` : ''}
                  </Badge>
                </TableCell>
                <TableCell className="text-mono py-3 font-mono text-[13px] whitespace-nowrap">
                  {row.ref || '—'}
                </TableCell>
                <TableCell className="py-3">{row.who ?? '—'}</TableCell>
                <TableCell className="text-mono py-3 text-end font-semibold tabular-nums">
                  {row.amount ?? '—'}
                </TableCell>
                <TableCell className="py-3 whitespace-nowrap">
                  {row.since ? formatDateTime(row.since) : '—'}
                </TableCell>
                <TableCell className="py-3 text-end">
                  <Button size="sm" variant="outline" asChild>
                    <Link href={row.href}>{__('Open')}</Link>
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        {rows.length === 0 && (
          <p className="text-secondary-foreground px-5 py-7 text-sm">
            {__('Nothing is waiting on you.')}
          </p>
        )}
      </CardTable>
    </Card>
  );
}
