'use client';
/**
 * FraudAnalyticsWidgets — four analytics widgets for the fraud dashboard.
 *
 * FraudEventsOverTime: CSS bar chart of fraud events per day (30d).
 * FalsePositiveRateWidget: per-adapter FP rate table + overall rate badge.
 * TopFiringAdaptersWidget: horizontal bar chart of top adapter+action combos (30d).
 * MoneyProtectedWidget: two currency figures — quarantined + recovered (90d).
 */
import { useT } from '@/lib/i18n/react';
import { Table } from '@/components/ui/primitives/Table';
import { Badge } from '@/components/ui/primitives/Badge';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip';
import { cn } from '@/lib/cn';
import { formatAgorotShekels } from '@/lib/money';

// ─── Row types (matched to DB query output) ───────────────────────────────────

export interface EventsOverTimeRow {
  day: string; // ISO date string
  action: 'block' | 'hold' | 'flag';
  count: number;
}

export interface FpRateRow {
  adapter: string;
  resolved_count: number;
  released_count: number;
  fp_rate_pct: number | null;
}

// ─── Constants ────────────────────────────────────────────────────────────────

const ACTION_COLOR: Record<'block' | 'hold' | 'flag', string> = {
  block: 'bg-danger-400',
  hold: 'bg-warning-400',
  flag: 'bg-neutral-400',
};

// ─── Badge tone helper ────────────────────────────────────────────────────────

type FpRateTone = 'neutral' | 'success' | 'warning' | 'danger';

function fpRateTone(rate: number | null): FpRateTone {
  if (rate === null) return 'neutral';
  if (rate < 10) return 'success';
  if (rate <= 25) return 'warning';
  return 'danger';
}

// ─── FraudEventsOverTime ──────────────────────────────────────────────────────

interface EvtOverTimeProps {
  rows: EventsOverTimeRow[];
}

export function FraudEventsOverTime({ rows }: EvtOverTimeProps) {
  const t = useT('admin_affiliates');

  if (rows.length === 0) {
    return (
      <div className="rounded-lg border border-(--color-border) bg-(--color-surface) p-4">
        <h2 className="mb-3 text-sm font-semibold text-(--color-text)">
          {t('fraud_widget_events_over_time_title')}
        </h2>
        <p className="text-sm text-(--color-text-subtle)">{t('fraud_widget_empty')}</p>
      </div>
    );
  }

  // Derive unique days and aggregate totals per day for bar height
  const dayMap = new Map<string, number>();
  for (const r of rows) {
    dayMap.set(r.day, (dayMap.get(r.day) ?? 0) + r.count);
  }
  const days = Array.from(dayMap.keys());
  const maxCount = Math.max(...dayMap.values(), 1);

  return (
    <div className="rounded-lg border border-(--color-border) bg-(--color-surface) p-4">
      <h2 className="mb-3 text-sm font-semibold text-(--color-text)">
        {t('fraud_widget_events_over_time_title')}
      </h2>

      {/* Screen-reader table */}
      <table className="sr-only">
        <caption>{t('fraud_widget_events_over_time_title')}</caption>
        <thead>
          <tr>
            <th scope="col">{t('fraud_widget_col_day')}</th>
            <th scope="col">{t('fraud_widget_col_action')}</th>
            <th scope="col">{t('fraud_widget_col_count')}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={`${r.day}-${r.action}`}>
              <td>{r.day}</td>
              <td>{r.action}</td>
              <td>{r.count}</td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* Visual bar chart — dir="ltr" so bars grow left→right regardless of page dir */}
      <div aria-hidden="true" dir="ltr" className="flex h-24 items-end gap-0.5 overflow-x-auto">
        {days.map((day) => {
          const total = dayMap.get(day) ?? 0;
          const heightPct = Math.round((total / maxCount) * 100);

          // Stack bars by action for this day
          const dayRows = rows.filter((r) => r.day === day);

          return (
            <div
              key={day}
              className="relative flex h-full min-w-1 flex-1 flex-col-reverse"
              title={day}
            >
              {dayRows.map((r) => {
                const segPct = Math.round((r.count / (dayMap.get(day) ?? 1)) * heightPct);
                return (
                  <div
                    key={r.action}
                    className={cn('w-full', ACTION_COLOR[r.action])}
                    style={{ height: `${segPct}%` }}
                  />
                );
              })}
            </div>
          );
        })}
      </div>

      {/* Legend */}
      <div className="mt-2 flex flex-wrap gap-3 text-xs text-(--color-text-subtle)">
        {(
          [
            ['block', 'fraud_severity_block'],
            ['hold', 'fraud_severity_hold'],
            ['flag', 'fraud_severity_flag'],
          ] as const
        ).map(([action, labelKey]) => (
          <span key={action} className="flex items-center gap-1">
            <span
              className={cn('inline-block h-2 w-2 rounded-sm', ACTION_COLOR[action])}
              aria-hidden
            />
            {t(labelKey)}
          </span>
        ))}
      </div>
    </div>
  );
}

// ─── FalsePositiveRateWidget ──────────────────────────────────────────────────

interface FpRateProps {
  rows: FpRateRow[];
  overallRate: number | null;
}

export function FalsePositiveRateWidget({ rows, overallRate }: FpRateProps) {
  const t = useT('admin_affiliates');

  const overallLabel =
    overallRate === null
      ? t('fraud_widget_fp_rate_no_data')
      : overallRate < 10
        ? t('fraud_widget_fp_rate_green')
        : overallRate <= 25
          ? t('fraud_widget_fp_rate_amber')
          : t('fraud_widget_fp_rate_red');

  return (
    <div className="rounded-lg border border-(--color-border) bg-(--color-surface) p-4">
      <div className="mb-3 flex items-center justify-between gap-2">
        <h2 className="text-sm font-semibold text-(--color-text)">
          {t('fraud_widget_fp_rate_title')}
        </h2>
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <Badge tone={fpRateTone(overallRate)} size="sm" className="cursor-help">
                {overallLabel}
              </Badge>
            </TooltipTrigger>
            <TooltipContent>{t('fraud_widget_fp_rate_tooltip')}</TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </div>

      {rows.length === 0 ? (
        <p className="text-sm text-(--color-text-subtle)">{t('fraud_widget_empty')}</p>
      ) : (
        <Table>
          <Table.Head className="border-b border-(--color-border-subtle)">
            <Table.Row>
              <Table.HeadCell className="py-1 pe-3 tracking-wide text-(--color-text-subtle) uppercase">
                {t('fraud_widget_col_adapter')}
              </Table.HeadCell>
              <Table.HeadCell className="py-1 pe-3 text-end tracking-wide text-(--color-text-subtle) uppercase">
                {t('fraud_widget_col_resolved')}
              </Table.HeadCell>
              <Table.HeadCell className="py-1 pe-3 text-end tracking-wide text-(--color-text-subtle) uppercase">
                {t('fraud_widget_col_released')}
              </Table.HeadCell>
              <Table.HeadCell className="py-1 text-end tracking-wide text-(--color-text-subtle) uppercase">
                {t('fraud_widget_col_fp_pct')}
              </Table.HeadCell>
            </Table.Row>
          </Table.Head>
          <Table.Body>
            {rows.map((r) => (
              <Table.Row key={r.adapter} className="border-b border-(--color-border-subtle)">
                <Table.Cell className="py-1 pe-3 text-(--color-text)">{r.adapter}</Table.Cell>
                <Table.Cell className="py-1 pe-3 text-end text-(--color-text) tabular-nums">
                  {r.resolved_count}
                </Table.Cell>
                <Table.Cell className="py-1 pe-3 text-end text-(--color-text) tabular-nums">
                  {r.released_count}
                </Table.Cell>
                <Table.Cell className="py-1 text-end">
                  <Badge tone={fpRateTone(r.fp_rate_pct)} size="sm">
                    {r.fp_rate_pct === null ? '–' : `${r.fp_rate_pct}%`}
                  </Badge>
                </Table.Cell>
              </Table.Row>
            ))}
          </Table.Body>
        </Table>
      )}
    </div>
  );
}

// ─── TopFiringAdaptersWidget ──────────────────────────────────────────────────

export interface TopAdapterRow {
  adapter: string;
  action: string;
  count: number;
}

export function TopFiringAdaptersWidget({ rows }: { rows: TopAdapterRow[] }) {
  const t = useT('admin_affiliates');

  if (rows.length === 0) {
    return (
      <div className="rounded-lg border border-(--color-border) bg-(--color-surface) p-4">
        <h2 className="mb-3 text-sm font-semibold text-(--color-text)">
          {t('fraud_widget_top_adapters_title')}
        </h2>
        <p className="text-sm text-(--color-text-subtle)">{t('fraud_widget_empty')}</p>
      </div>
    );
  }

  const maxCount = Math.max(...rows.map((r) => r.count), 1);

  return (
    <div className="rounded-lg border border-(--color-border) bg-(--color-surface) p-4">
      <h2 className="mb-3 text-sm font-semibold text-(--color-text)">
        {t('fraud_widget_top_adapters_title')}
      </h2>

      {/* Screen-reader table */}
      <table className="sr-only">
        <caption>{t('fraud_widget_top_adapters_title')}</caption>
        <thead>
          <tr>
            <th scope="col">{t('fraud_widget_col_adapter')}</th>
            <th scope="col">{t('fraud_widget_col_action')}</th>
            <th scope="col">{t('fraud_widget_col_count')}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={`${r.adapter}-${r.action}`}>
              <td>{r.adapter}</td>
              <td>{r.action}</td>
              <td>{r.count}</td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* Visual horizontal bars — dir="ltr" so bar widths grow left→right */}
      <div aria-hidden="true" className="flex flex-col gap-1.5">
        {rows.map((r) => {
          const widthPct = Math.round((r.count / maxCount) * 100);
          return (
            <div key={`${r.adapter}-${r.action}`} className="flex items-center gap-2 text-xs">
              <span className="w-28 shrink-0 truncate text-end text-(--color-text-subtle)">
                {r.adapter}
              </span>
              <Badge tone="neutral" size="sm" className="w-12 shrink-0 justify-center text-center">
                {r.action}
              </Badge>
              <div className="flex-1 overflow-hidden rounded-sm bg-(--color-border-subtle)">
                <div
                  dir="ltr"
                  className="bg-warning-400 h-3 rounded-sm"
                  style={{ width: `${widthPct}%` }}
                />
              </div>
              <span className="w-8 shrink-0 text-end text-(--color-text) tabular-nums">
                {r.count}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── MoneyProtectedWidget ─────────────────────────────────────────────────────

export function MoneyProtectedWidget({
  quarantinedAgorot,
  recovered90dAgorot,
}: {
  quarantinedAgorot: number;
  recovered90dAgorot: number;
}) {
  const t = useT('admin_affiliates');

  return (
    <div className="rounded-lg border border-(--color-border) bg-(--color-surface) p-4">
      <h2 className="mb-4 text-sm font-semibold text-(--color-text)">
        {t('fraud_widget_money_protected_title')}
      </h2>
      <dl className="flex flex-col gap-3">
        <div className="flex items-center justify-between gap-2">
          <dt className="text-sm text-(--color-text-subtle)">
            {t('fraud_widget_money_quarantined_label')}
          </dt>
          <dd className="text-sm font-semibold text-(--color-text) tabular-nums">
            {formatAgorotShekels(quarantinedAgorot)}
          </dd>
        </div>
        <div className="flex items-center justify-between gap-2">
          <dt className="text-sm text-(--color-text-subtle)">
            {t('fraud_widget_money_recovered_label')}
          </dt>
          <dd className="text-success-700 text-sm font-semibold tabular-nums">
            {formatAgorotShekels(recovered90dAgorot)}
          </dd>
        </div>
      </dl>
    </div>
  );
}
