/**
 * VendorAnalytics — /vendor/analytics page feature (C2.4).
 *
 * - Date-range picker: 7d / 30d / 90d / custom
 * - Compare-to-previous-period toggle
 * - VendorFunnelChart (getVendorFunnel)
 * - Revenue line chart (getVendorRevenueSeries) — simple SVG bar chart
 * - Category bars (getVendorCategoryBreakdown)
 * - Per-deal leaderboard (listTopDealsByVendor)
 */

'use client';

import type { DehydratedState } from '@tanstack/react-query';
import { useState } from 'react';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { QueryBoundary } from '@platform-modules/ui-primitives';
import { HydratedIsland } from '@/components/HydratedIsland';
import { VendorShell } from '@/components/ui/layout/VendorShell';
import { VendorFunnelChart } from '@/components/ui/domain/vendor/VendorFunnelChart';
import type { FunnelStep } from '@/components/ui/domain/vendor/VendorFunnelChart';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { Button } from '@/components/ui/primitives/Button';
import { useT, useLocale } from '@/lib/i18n/react';
import { formatCurrency, formatDateShort } from '@/lib/format';
import { interpolate } from '@/lib/i18n/interpolate';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip';
import { Table } from '@/components/ui/primitives/Table';
import { Skeleton } from '@/components/ui/feedback/Skeleton';
import type { DashboardPrefetchDescriptor } from '@/lib/query/prefetch-registry';
import { SegmentedControl } from '@/components/ui/primitives/SegmentedControl';
import { MetricTile } from '@/components/ui/domain/MetricTile';
import { useDashboardDensity } from '@/features/dashboards/useDashboardDensity';

type RangeKey = '7d' | '30d' | '90d';

interface RevenuePoint {
  date: string;
  revenue: number;
  orders: number;
}
interface CategoryRow {
  category: string;
  dealCount: number;
  totalRevenue: number;
  totalOrders: number;
}
interface TopDealRow {
  dealId: string;
  title: string;
  quantitySold: number;
  quantityTotal: number;
  totalRevenue: number;
  conversionRate: number;
}
interface VendorFunnelRow {
  totalDeals: number;
  activeDeals: number;
  soldOutDeals: number;
  totalPurchases: number;
  totalQuantitySold: number;
  avgConversionRate: number;
}

interface AnalyticsData {
  funnel: VendorFunnelRow | null;
  revenueSeries: RevenuePoint[];
  categoryBreakdown: CategoryRow[];
  topDeals: TopDealRow[];
  periodComparison: unknown | null;
}

const VENDOR_ANALYTICS_DEFAULT_RANGE = '30d' as const;

function rangeFromLocation(): RangeKey {
  if (typeof window === 'undefined') return VENDOR_ANALYTICS_DEFAULT_RANGE;
  const value = new URL(window.location.href).searchParams.get('range');
  return value === '7d' || value === '90d' ? value : VENDOR_ANALYTICS_DEFAULT_RANGE;
}

// ─── Hook ─────────────────────────────────────────────────────────────────────

function useAnalytics(range: RangeKey) {
  return useQuery<AnalyticsData>({
    queryKey: vendorAnalyticsQueryKey(range),
    queryFn: () => fetchVendorAnalytics(range),
    staleTime: 60_000,
    placeholderData: keepPreviousData,
  });
}

export function vendorAnalyticsQueryKey(range: RangeKey) {
  return ['vendor-analytics', range] as const;
}

export async function fetchVendorAnalytics(range: RangeKey): Promise<AnalyticsData> {
  const res = await fetch(`/api/vendor/analytics?range=${range}&compare=false`);
  if (!res.ok) throw new Error('Failed to load analytics');
  return ((await res.json()) as { data: AnalyticsData }).data;
}

export const VENDOR_ANALYTICS_PREFETCH_DESCRIPTOR: DashboardPrefetchDescriptor = {
  href: '/vendor/analytics',
  queryKey: vendorAnalyticsQueryKey(VENDOR_ANALYTICS_DEFAULT_RANGE),
  queryFn: () => fetchVendorAnalytics(VENDOR_ANALYTICS_DEFAULT_RANGE),
  staleTime: 60_000,
};

function VendorAnalyticsSkeleton() {
  return (
    <div
      className="flex flex-col gap-6 p-4 lg:p-6"
      aria-hidden="true"
      data-testid="instant-skeleton:vendor-analytics"
    >
      <div className="flex flex-wrap items-center gap-3">
        <Skeleton className="h-9 w-56" />
      </div>
      <Skeleton className="h-44 w-full" />
      <Skeleton className="h-56 w-full" />
      <Skeleton className="h-48 w-full" />
    </div>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────

function VendorAnalyticsInner() {
  const t = useT('vendor_analytics');
  const [range, setRange] = useState<RangeKey>(rangeFromLocation);
  const { density, setDensity } = useDashboardDensity('dashboard-density:vendor-analytics');
  const analyticsQuery = useAnalytics(range);

  function selectRange(value: RangeKey) {
    setRange(value);
    const url = new URL(window.location.href);
    url.searchParams.set('range', value);
    window.history.replaceState(window.history.state, '', url);
  }

  const ranges: { key: RangeKey; label: string }[] = [
    { key: '7d', label: t('range_7d') },
    { key: '30d', label: t('range_30d') },
    { key: '90d', label: t('range_90d') },
  ];

  return (
    <VendorShell variant="dashboard" currentPath="/vendor/analytics">
      <div className="flex flex-col gap-6 p-4 lg:p-6">
        <QueryBoundary
          query={analyticsQuery}
          skeleton={<VendorAnalyticsSkeleton />}
          errorFallback={() => (
            <ErrorState
              title={t('error_title')}
              description={t('error_desc')}
              action={
                <Button variant="primary" size="sm" onClick={() => void analyticsQuery.refetch()}>
                  {t('retry')}
                </Button>
              }
            />
          )}
        >
          {(data) => {
            const hasFunnel = Boolean(data.funnel && data.funnel.totalDeals > 0);
            const hasRevenue = data.revenueSeries.length > 0;
            const hasCategories = data.categoryBreakdown.length > 0;
            const hasTopDeals = data.topDeals.length > 0;
            const isEmpty = !hasFunnel && !hasRevenue && !hasCategories && !hasTopDeals;

            if (isEmpty) {
              return (
                <EmptyState
                  title={t('empty_title')}
                  description={t('empty_desc')}
                  action={
                    <Button variant="primary" size="sm" asChild>
                      <a href="/vendor/deals">{t('empty_action')}</a>
                    </Button>
                  }
                />
              );
            }

            const rangeLabel = ranges.find((item) => item.key === range)?.label ?? t('range_30d');
            const heroRevenue = data.revenueSeries.reduce((sum, point) => sum + point.revenue, 0);

            return (
              <div className="flex flex-col gap-6" data-testid="instant-content:vendor-analytics">
                <section className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_16rem]">
                  <div className="space-y-3">
                    <div>
                      <h2 className="text-text-primary text-2xl font-bold">{t('page_title')}</h2>
                      <p className="text-text-muted mt-1 text-sm">
                        {t('hero_period_prefix').replace('{{period}}', rangeLabel)}
                      </p>
                    </div>
                    <div className="flex flex-wrap gap-3">
                      <SegmentedControl
                        aria-label={t('range_group_label')}
                        value={range}
                        onChange={(value) => selectRange(value as RangeKey)}
                        options={ranges.map((item) => ({ value: item.key, label: item.label }))}
                      />
                      <SegmentedControl
                        aria-label={t('density_label')}
                        size="sm"
                        value={density}
                        onChange={(value) => setDensity(value as 'comfortable' | 'dense')}
                        options={[
                          { value: 'comfortable', label: t('density_comfortable') },
                          { value: 'dense', label: t('density_dense') },
                        ]}
                      />
                    </div>
                  </div>
                  <MetricTile
                    label={t('hero_metric_label')}
                    value={formatCurrency(heroRevenue)}
                    countUpValue={heroRevenue}
                    formatCountUpValue={(value) => formatCurrency(value)}
                    periodLabel={rangeLabel}
                    sparklinePoints={data.revenueSeries.map((point) => point.revenue)}
                    sparklineLabel={t('hero_sparkline_label')}
                    tone="success"
                  />
                </section>

                {/* Funnel */}
                {data.funnel && (
                  <section aria-labelledby="funnel-heading">
                    <div className="mb-3 flex flex-wrap items-baseline gap-2">
                      <h2 id="funnel-heading" className="text-text-primary text-sm font-semibold">
                        {t('funnel_title')}
                      </h2>
                      <span className="text-text-muted text-xs">{t('range_all_time')}</span>
                    </div>
                    <VendorFunnelChart steps={funnelToSteps(data.funnel)} />
                  </section>
                )}

                {/* Revenue series */}
                {data.revenueSeries.length > 0 && (
                  <section aria-labelledby="revenue-heading">
                    <h2
                      id="revenue-heading"
                      className="text-text-primary mb-3 text-sm font-semibold"
                    >
                      {t('revenue_title')}
                    </h2>
                    <RevenueBarChart series={data.revenueSeries} />
                  </section>
                )}

                {/* Category breakdown */}
                {data.categoryBreakdown.length > 0 && (
                  <section aria-labelledby="category-heading">
                    <div className="mb-3 flex flex-wrap items-baseline gap-2">
                      <h2 id="category-heading" className="text-text-primary text-sm font-semibold">
                        {t('category_title')}
                      </h2>
                      <span className="text-text-muted text-xs">{t('range_all_time')}</span>
                    </div>
                    <CategoryBars rows={data.categoryBreakdown} />
                  </section>
                )}

                {/* Leaderboard */}
                {data.topDeals.length > 0 && (
                  <section aria-labelledby="leaderboard-heading">
                    <h2
                      id="leaderboard-heading"
                      className="text-text-primary mb-3 text-sm font-semibold"
                    >
                      {t('leaderboard_title')}
                    </h2>
                    <Leaderboard deals={data.topDeals} dense={density === 'dense'} />
                  </section>
                )}
              </div>
            );
          }}
        </QueryBoundary>
      </div>
    </VendorShell>
  );
}

// ─── Export wrapper ───────────────────────────────────────────────────────────

export interface VendorAnalyticsProps {
  dehydratedState?: DehydratedState;
}

export function VendorAnalytics({ dehydratedState }: VendorAnalyticsProps) {
  return (
    <HydratedIsland dehydratedState={dehydratedState}>
      <VendorAnalyticsInner />
    </HydratedIsland>
  );
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function funnelToSteps(funnel: VendorFunnelRow): FunnelStep[] {
  return [
    { key: 'total_deals', value: funnel.totalDeals },
    { key: 'active_deals', value: funnel.activeDeals },
    { key: 'units_sold', value: funnel.totalQuantitySold },
    { key: 'orders', value: funnel.totalPurchases },
  ];
}

// ─── Revenue bar chart (simple CSS bars — no external chart lib) ──────────────

function RevenueBarChart({ series }: { series: RevenuePoint[] }) {
  const t = useT('vendor_analytics');
  const { locale } = useLocale();
  const maxRev = Math.max(...series.map((p) => p.revenue), 1);
  return (
    <TooltipProvider>
      <div
        className="flex items-end gap-1 overflow-x-auto py-2"
        role="img"
        aria-label={t('revenue_title')}
      >
        {series.map((p) => {
          const pct = Math.max(4, (p.revenue / maxRev) * 100);
          const dateLabel = formatDateShort(p.date, locale);
          const tip = interpolate(t('bar_tooltip'), {
            amount: formatCurrency(p.revenue, locale),
            orders: String(p.orders),
          });
          return (
            <div key={p.date} className="flex flex-col items-center gap-1">
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="focus-visible:outline-brand-primary-500 flex h-auto flex-col items-center gap-1 rounded-sm p-0 shadow-none focus-visible:outline-2 focus-visible:outline-offset-1"
                    aria-label={`${dateLabel}: ${tip}`}
                  >
                    <div
                      className="bg-mode-vendor-500 w-6 rounded-t transition-all"
                      style={{ height: `${pct.toFixed(0)}px` }}
                      aria-hidden
                    />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>{tip}</TooltipContent>
              </Tooltip>
              <span className="text-text-muted text-2xs w-6 text-center leading-none">
                {dateLabel}
              </span>
            </div>
          );
        })}
      </div>
    </TooltipProvider>
  );
}

// ─── Category bars ────────────────────────────────────────────────────────────

function CategoryBars({ rows }: { rows: CategoryRow[] }) {
  const t = useT('vendor_analytics');
  const maxRev = Math.max(...rows.map((r) => r.totalRevenue), 1);
  return (
    <ul className="flex flex-col gap-2">
      {rows.map((row) => {
        const pct = Math.max(2, (row.totalRevenue / maxRev) * 100);
        const label =
          row.category === 'Uncategorized' || row.category === '__uncategorized__'
            ? t('uncategorized')
            : row.category;
        return (
          <li key={row.category} className="flex items-center gap-3">
            <span className="text-text-secondary w-24 shrink-0 text-xs" data-testid="deal-title">
              {label}
            </span>
            <div className="bg-surface-raised border-border relative h-5 flex-1 overflow-hidden rounded border">
              <div
                className="bg-mode-vendor-400 h-full rounded transition-all"
                style={{ width: `${pct.toFixed(0)}%` }}
                aria-hidden
              />
            </div>
            <span className="text-text-primary w-20 text-end text-xs tabular-nums">
              {formatCurrency(row.totalRevenue)}
            </span>
          </li>
        );
      })}
    </ul>
  );
}

// ─── Leaderboard ─────────────────────────────────────────────────────────────

function Leaderboard({ deals, dense = false }: { deals: TopDealRow[]; dense?: boolean }) {
  const t = useT('vendor_analytics');
  return (
    <Table className={dense ? 'text-sm' : undefined}>
      <Table.Head className="bg-surface-app">
        <Table.Row>
          <Table.HeadCell className="pb-2 font-medium">{t('leaderboard_deal')}</Table.HeadCell>
          <Table.HeadCell className="pb-2 text-end font-medium">
            {t('leaderboard_sold')}
          </Table.HeadCell>
          <Table.HeadCell className="pb-2 text-end font-medium">
            {t('leaderboard_revenue')}
          </Table.HeadCell>
          <Table.HeadCell className="pb-2 text-end font-medium">
            {t('leaderboard_conversion')}
          </Table.HeadCell>
        </Table.Row>
      </Table.Head>
      <Table.Body>
        {deals.map((d) => (
          <Table.Row key={d.dealId}>
            <Table.Cell className={dense ? 'py-1.5' : 'py-2'} data-testid="deal-title">
              {d.title}
            </Table.Cell>
            <Table.Cell
              className={dense ? 'py-1.5 text-end tabular-nums' : 'py-2 text-end tabular-nums'}
            >
              {d.quantitySold}
            </Table.Cell>
            <Table.Cell
              className={dense ? 'py-1.5 text-end tabular-nums' : 'py-2 text-end tabular-nums'}
            >
              {formatCurrency(d.totalRevenue)}
            </Table.Cell>
            <Table.Cell
              className={dense ? 'py-1.5 text-end tabular-nums' : 'py-2 text-end tabular-nums'}
            >
              {(d.conversionRate * 100).toFixed(0)}%
            </Table.Cell>
          </Table.Row>
        ))}
      </Table.Body>
    </Table>
  );
}
