import { useState, type ReactNode } from 'react';
import { Button } from '@/components/ui/primitives/Button';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useT } from '@/lib/i18n/react';
import { SegmentedControl } from '@/components/ui/primitives/SegmentedControl';
import { cn } from '@/lib/cn';
import { MetricTile } from '@/components/ui/domain/MetricTile';
import { formatAgorotShekels } from '@/lib/money';

type Window = '1d' | '7d' | '30d' | '90d' | 'all';

type StatsData = {
  referrals: number;
  conversions: number;
  earned_agorot: number;
};

const WINDOWS: Window[] = ['1d', '7d', '30d', '90d', 'all'];

function MetricTileWithTooltip({
  label,
  tooltip,
  value,
  loading,
  className,
}: {
  label: string;
  tooltip?: string;
  value: ReactNode;
  loading?: boolean;
  className?: string;
}) {
  if (loading) {
    return <MetricTile label={label} value="" loading className={className} />;
  }

  return (
    <div
      className={cn(
        'bg-surface-raised text-text-primary flex flex-col items-center justify-center gap-1 rounded-xl p-4 text-center',
        className,
      )}
    >
      <span className="text-3xl leading-tight font-bold">{value}</span>
      {tooltip ? (
        <LabelWithTooltip label={label} tooltip={tooltip} />
      ) : (
        <span className="text-xs font-medium opacity-80">{label}</span>
      )}
    </div>
  );
}

export function AffiliateStatsWindow() {
  const t = useT('affiliate');
  const tCommon = useT('common');
  const [activeWindow, setActiveWindow] = useState<Window>('30d');

  const { data, isLoading, isError, refetch } = useQuery<StatsData>({
    queryKey: ['affiliate-stats', activeWindow],
    queryFn: async () => {
      const res = await fetch(`/api/affiliate/stats?window=${activeWindow}`);
      if (!res.ok) throw new Error(await res.text());
      const json = (await res.json()) as { data: StatsData };
      return json.data;
    },
    placeholderData: keepPreviousData,
  });

  const convRate =
    data && data.referrals > 0 ? `${((data.conversions / data.referrals) * 100).toFixed(1)}%` : '—';

  if (isError) {
    return (
      <ErrorState
        title={tCommon('error_loading')}
        action={
          <Button variant="secondary" size="sm" onClick={() => refetch()}>
            {tCommon('retry')}
          </Button>
        }
      />
    );
  }
  return (
    <section aria-label={t('dashboard_heading')}>
      <div className="flex flex-col gap-4">
        <SegmentedControl
          aria-label={t('window_selector_label')}
          value={activeWindow}
          onChange={(value) => setActiveWindow(value as Window)}
          options={WINDOWS.map((window) => ({
            value: window,
            label: t(`window_${window}` as Parameters<typeof t>[0]),
          }))}
        />
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
          <MetricTile
            label={t('metric_clicks')}
            value={t('metric_deferred_short')}
            className="opacity-60"
            periodLabel={t(`window_${activeWindow}` as Parameters<typeof t>[0])}
          />
          <MetricTileWithTooltip
            label={t('metric_referrals')}
            tooltip={t('tooltip_metric_referrals')}
            value={isLoading ? undefined : (data?.referrals ?? 0)}
            loading={isLoading}
          />
          <MetricTileWithTooltip
            label={t('metric_conversions')}
            tooltip={t('tooltip_metric_conversions')}
            value={isLoading ? undefined : (data?.conversions ?? 0)}
            loading={isLoading}
          />
          <MetricTile
            label={t('metric_earned')}
            value={isLoading ? undefined : formatAgorotShekels(data?.earned_agorot ?? 0)}
            loading={isLoading}
            periodLabel={t(`window_${activeWindow}` as Parameters<typeof t>[0])}
          />
          <MetricTile
            label={t('metric_ctr')}
            value={t('metric_deferred_short')}
            className="opacity-60"
            periodLabel={t(`window_${activeWindow}` as Parameters<typeof t>[0])}
          />
          <MetricTileWithTooltip
            label={t('metric_conv_rate')}
            tooltip={t('tooltip_metric_conv_rate')}
            value={isLoading ? undefined : convRate}
            loading={isLoading}
          />
        </div>
        <div className="border-border-subtle bg-surface-raised rounded-xl border p-4">
          <p className="text-text-primary text-sm font-semibold">{t('deferred_title')}</p>
          <ul className="text-text-muted mt-2 flex list-disc flex-col gap-1 ps-5 text-sm">
            <li>{t('deferred_clicks')}</li>
            <li>{t('deferred_ctr')}</li>
          </ul>
        </div>
      </div>
    </section>
  );
}
