'use client';

import { QueryBoundary } from '@platform-modules/ui-primitives';
import { useQuery } from '@tanstack/react-query';
import { useLocale, useT } from '@/lib/i18n/react';
import { formatDate } from '@/lib/format';
import { formatAgorotShekels, formatAgorotSigned } from '@/lib/money';
import { Table } from '@/components/ui/primitives/Table';
import { Badge } from '@/components/ui/primitives/Badge';
import { Button } from '@/components/ui/primitives/Button';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { TableSkeleton } from '@/components/ui/feedback/Skeleton';

type NegativeWalletRow = {
  enrollmentId: string;
  userId: string;
  email: string | null;
  netMaturedAgorot: number;
  debtAgorot: number;
  debtStartedAt: string | null;
  debtAgeDays: number | null;
  uncollectable: boolean;
};

type NegativeWalletResponse = { items: NegativeWalletRow[] };

async function fetchNegativeWallets(): Promise<NegativeWalletResponse> {
  const response = await fetch('/api/admin/affiliates/negative-wallets');
  if (!response.ok) throw new Error('NEGATIVE_WALLETS_LOAD_FAILED');
  const json = (await response.json()) as { data?: NegativeWalletResponse };
  return json.data ?? { items: [] };
}

export function NegativeWalletsPanel() {
  const t = useT('admin_affiliates');
  const tCommon = useT('common');
  const { locale } = useLocale();
  const query = useQuery({
    queryKey: ['admin-negative-affiliate-wallets'],
    queryFn: fetchNegativeWallets,
  });

  return (
    <QueryBoundary
      query={query}
      skeleton={<TableSkeleton rows={3} cols={6} />}
      errorFallback={(retry) => (
        <ErrorState
          title={tCommon('error_loading')}
          action={
            <Button variant="secondary" size="sm" onClick={() => retry()}>
              {tCommon('retry')}
            </Button>
          }
        />
      )}
    >
      {(resolved) => (
        <section aria-labelledby="negative-wallets-heading" className="space-y-3">
          <div>
            <h2 id="negative-wallets-heading" className="font-semibold">
              {t('negative_wallets_title')}
            </h2>
            <p className="text-text-muted text-sm">{t('negative_wallets_description')}</p>
          </div>

          {!resolved.items.length ? (
            <EmptyState title={t('negative_wallets_empty')} />
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <Table.Head>
                  <Table.Row>
                    <Table.HeadCell>{t('negative_wallets_col_email')}</Table.HeadCell>
                    <Table.HeadCell>{t('negative_wallets_col_net')}</Table.HeadCell>
                    <Table.HeadCell>{t('negative_wallets_col_debt')}</Table.HeadCell>
                    <Table.HeadCell>{t('negative_wallets_col_debt_started')}</Table.HeadCell>
                    <Table.HeadCell>{t('negative_wallets_col_debt_age')}</Table.HeadCell>
                    <Table.HeadCell>{t('negative_wallets_col_class')}</Table.HeadCell>
                  </Table.Row>
                </Table.Head>
                <Table.Body>
                  {resolved.items.map((row) => (
                    <Table.Row key={row.enrollmentId}>
                      <Table.Cell className="py-3 pe-4">
                        {row.email ?? t('negative_wallets_unknown')}
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4 tabular-nums">
                        {formatAgorotSigned(row.netMaturedAgorot)}
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4 tabular-nums">
                        {formatAgorotShekels(row.debtAgorot)}
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4">
                        {row.debtStartedAt
                          ? formatDate(row.debtStartedAt, locale)
                          : t('negative_wallets_unknown')}
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4 tabular-nums">
                        {row.debtAgeDays === null
                          ? t('negative_wallets_unknown')
                          : `${row.debtAgeDays} ${t('negative_wallets_days')}`}
                      </Table.Cell>
                      <Table.Cell className="py-3">
                        <Badge tone={row.uncollectable ? 'danger' : 'warning'} size="sm">
                          {row.uncollectable
                            ? t('negative_wallets_uncollectable')
                            : t('negative_wallets_carried')}
                        </Badge>
                      </Table.Cell>
                    </Table.Row>
                  ))}
                </Table.Body>
              </Table>
            </div>
          )}
        </section>
      )}
    </QueryBoundary>
  );
}
