import { useT, useLocale } from '@/lib/i18n/react';
import { usePaginatedQuery } from '@/lib/hooks/usePaginatedQuery';
import { QueryBoundary } from '@platform-modules/ui-primitives';
import { Table } from '@/components/ui/primitives/Table';
import { Pagination } from '@/components/ui/primitives/Pagination';
import { StatusBadge, type StatusEntry } from '@/components/ui/domain/StatusBadge';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip';
import { formatDate } from '@/lib/format';
import { HydratedIsland } from '@/components/HydratedIsland';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { Button } from '@/components/ui/primitives/Button';
import { Skeleton, TableSkeleton } from '@/components/ui/feedback/Skeleton';
import {
  AffiliateLtvMarginValue,
  AffiliateTotalPayoutsValue,
  type AffiliateLtvData,
} from './affiliateLtvUi';
import { NegativeWalletsPanel } from './NegativeWalletsPanel';

type AffiliateStatus = 'active' | 'suspended' | 'revoked';

type AffiliateListRow = {
  id: string;
  user_id: string;
  email: string | null;
  status: AffiliateStatus;
  pct: number | null;
  created_at: string;
  ltv?: AffiliateLtvData;
};

type AffiliateListResolved = {
  items: AffiliateListRow[];
  totalPages: number;
  page: number;
};

const AFFILIATE_STATUS_MAP: Record<AffiliateStatus, StatusEntry> = {
  active: { tone: 'success', labelKey: 'status_active' },
  suspended: { tone: 'warning', labelKey: 'status_suspended' },
  revoked: { tone: 'danger', labelKey: 'status_revoked' },
};

function HeadCellWithTooltip({
  label,
  tooltip,
  className,
}: {
  label: string;
  tooltip?: string;
  className?: string;
}) {
  if (!tooltip) {
    return <Table.HeadCell className={className}>{label}</Table.HeadCell>;
  }
  return (
    <Table.HeadCell className={className}>
      <Tooltip>
        <TooltipTrigger asChild>
          <span className="cursor-help border-b border-dotted border-(--color-border)">
            {label}
          </span>
        </TooltipTrigger>
        <TooltipContent>{tooltip}</TooltipContent>
      </Tooltip>
    </Table.HeadCell>
  );
}

function AffiliateListSkeleton() {
  return (
    <div aria-hidden="true" role="presentation">
      <TableSkeleton rows={5} cols={7} />
      <div className="mt-4 flex justify-end">
        <Skeleton className="h-9 w-40" />
      </div>
    </div>
  );
}

function AffiliateListInner() {
  const t = useT('admin_affiliates');
  const tCommon = useT('common');
  const { locale } = useLocale();

  const {
    data: items,
    totalPages,
    page,
    isInitialLoading,
    error,
    setPage,
    refetch,
  } = usePaginatedQuery<AffiliateListRow>({
    endpoint: '/api/admin/affiliates',
    limit: 20,
    initialData: [],
    initialTotal: 0,
    dataKey: 'items',
  });

  const affiliateListQuery = {
    data: isInitialLoading
      ? undefined
      : ({ items, totalPages, page } satisfies AffiliateListResolved),
    isLoading: isInitialLoading,
    isPending: isInitialLoading,
    isError: Boolean(error),
    error: error ? new Error(error) : null,
    refetch,
  };

  return (
    <QueryBoundary
      query={affiliateListQuery}
      skeleton={<AffiliateListSkeleton />}
      errorFallback={() => (
        <ErrorState
          title={tCommon('error_loading')}
          action={
            <Button variant="secondary" size="sm" onClick={() => refetch()}>
              {tCommon('retry')}
            </Button>
          }
        />
      )}
    >
      {(resolved) => {
        if (!resolved.items.length) {
          return <EmptyState title={t('list_empty')} description={t('list_empty_description')} />;
        }

        return (
          <TooltipProvider>
            <Table>
              <Table.Head>
                <Table.Row>
                  <Table.HeadCell className="pe-4 pb-3">{t('list_col_email')}</Table.HeadCell>
                  <Table.HeadCell className="pe-4 pb-3">{t('list_col_status')}</Table.HeadCell>
                  <HeadCellWithTooltip
                    className="pe-4 pb-3"
                    label={t('list_col_pct')}
                    tooltip={t('list_col_pct_tooltip')}
                  />
                  <HeadCellWithTooltip
                    className="pe-4 pb-3"
                    label={t('list_col_ltv')}
                    tooltip={t('list_col_ltv_tooltip')}
                  />
                  <HeadCellWithTooltip
                    className="pe-4 pb-3"
                    label={t('list_col_total_payouts')}
                    tooltip={t('list_col_payouts_tooltip')}
                  />
                  <Table.HeadCell className="pe-4 pb-3">{t('list_col_joined')}</Table.HeadCell>
                  <Table.HeadCell className="pb-3"></Table.HeadCell>
                </Table.Row>
              </Table.Head>
              <Table.Body>
                {resolved.items.map((row) => {
                  const statusTooltipKey =
                    row.status === 'suspended'
                      ? 'status_suspended_tooltip'
                      : row.status === 'revoked'
                        ? 'status_revoked_tooltip'
                        : null;
                  const badge = (
                    <StatusBadge
                      state={row.status}
                      map={AFFILIATE_STATUS_MAP}
                      ns="admin_affiliates"
                      size="sm"
                    />
                  );

                  return (
                    <Table.Row key={row.id} className="hover:bg-(--color-surface-hover)">
                      <Table.Cell className="py-3 pe-4">{row.email ?? '—'}</Table.Cell>
                      <Table.Cell className="py-3 pe-4">
                        {statusTooltipKey ? (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <span className="cursor-help">{badge}</span>
                            </TooltipTrigger>
                            <TooltipContent>{t(statusTooltipKey)}</TooltipContent>
                          </Tooltip>
                        ) : (
                          badge
                        )}
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4 tabular-nums">
                        {row.pct !== null ? `${row.pct}%` : t('list_pct_default')}
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4">
                        <AffiliateLtvMarginValue ltv={row.ltv} t={t} />
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4">
                        <AffiliateTotalPayoutsValue ltv={row.ltv} />
                      </Table.Cell>
                      <Table.Cell className="py-3 pe-4">
                        {formatDate(row.created_at, locale)}
                      </Table.Cell>
                      <Table.Cell className="py-3">
                        <a
                          href={`/admin/affiliates/${row.id}`}
                          className="text-(--color-primary) hover:underline"
                        >
                          {t('list_view')}
                        </a>
                      </Table.Cell>
                    </Table.Row>
                  );
                })}
              </Table.Body>
            </Table>

            {resolved.totalPages > 1 && (
              <div className="mt-4">
                <Pagination
                  page={resolved.page}
                  totalPages={resolved.totalPages}
                  onPageChange={setPage}
                />
              </div>
            )}
          </TooltipProvider>
        );
      }}
    </QueryBoundary>
  );
}

export function AffiliateList() {
  return (
    <HydratedIsland>
      <div className="space-y-8">
        <AffiliateListInner />
        <NegativeWalletsPanel />
      </div>
    </HydratedIsland>
  );
}
