'use client';

import { useState, useEffect } from 'react';
import {
  QueryClient,
  QueryClientProvider,
  useQuery,
  keepPreviousData,
} from '@tanstack/react-query';
import { ScrollRow } from '@/components/ui/layout/ScrollRow';
import { DealCard, type DealCardDeal } from '@/components/ui/domain/DealCard';
import { Button } from '@/components/ui/primitives/Button';
import { useLocale, useT } from '@/lib/i18n/react';
import type { Config } from './config';
import type { HotDealsModuleData } from './loadData';
import type { HotDealWindow } from '@/server/catalog/public/hot';
import { EmptyRowHeading, useShouldRenderEmptyRow } from '../_shared/EmptyRowHeading';
import { qk } from '@/lib/query/keys';

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1 } },
});

async function fetchHotDeals(
  window: HotDealWindow,
  locale: string,
  limit: number,
): Promise<DealCardDeal[]> {
  const res = await fetch(`/api/deals/hot?window=${window}&locale=${locale}&limit=${limit}`);
  if (!res.ok) return [];
  const json = (await res.json()) as { ok: boolean; deals?: DealCardDeal[] };
  return json.deals ?? [];
}

const WINDOWS: {
  key: HotDealWindow;
  labelKey: 'hot_deals_today' | 'hot_deals_7d' | 'hot_deals_30d';
}[] = [
  { key: '24h', labelKey: 'hot_deals_today' },
  { key: '7d', labelKey: 'hot_deals_7d' },
  { key: '30d', labelKey: 'hot_deals_30d' },
];

export function Component({
  config,
  data,
  demo,
}: {
  config: Config;
  data: unknown;
  demo?: boolean;
}) {
  // Gallery demo passes a bare DealCardDeal[] — normalize to module data shape.
  const parsed = Array.isArray(data)
    ? { deals: data as DealCardDeal[], activeWindow: '24h' as HotDealWindow }
    : (data as HotDealsModuleData | null);
  return (
    <QueryClientProvider client={queryClient}>
      <HotDealsInner config={config} ssrData={parsed} demo={demo} />
    </QueryClientProvider>
  );
}

function HotDealsInner({
  config,
  ssrData,
  demo,
}: {
  config: Config;
  ssrData: HotDealsModuleData | null;
  demo?: boolean;
}) {
  const { locale } = useLocale();
  const tFeed = useT('feed');
  const isPreview = useShouldRenderEmptyRow();
  const title = config.title[locale];

  const [activeWindow, setActiveWindow] = useState<HotDealWindow>(ssrData?.activeWindow ?? '24h');

  // Prefetch other windows after hydration so toggle is instant
  useEffect(() => {
    if (demo) return;
    queryClient.prefetchQuery({
      queryKey: qk.hotDeals('7d', locale),
      queryFn: () => fetchHotDeals('7d', locale, config.limit),
    });
    queryClient.prefetchQuery({
      queryKey: qk.hotDeals('30d', locale),
      queryFn: () => fetchHotDeals('30d', locale, config.limit),
    });
  }, [locale, config.limit, demo]);

  const { data: currentDeals = [] } = useQuery({
    queryKey: qk.hotDeals(activeWindow, locale),
    queryFn: () => fetchHotDeals(activeWindow, locale, config.limit),
    staleTime: 5 * 60 * 1000,
    // SSR window: seed from server data so no flicker on mount (treated stale → silent bg refetch).
    // Demo: seed every window so the gallery preview never fetches or empties.
    initialData:
      demo || activeWindow === ssrData?.activeWindow ? (ssrData?.deals ?? undefined) : undefined,
    // Non-SSR windows: keep previous tab's deals visible while new tab loads → no flash
    placeholderData: keepPreviousData,
    enabled: !demo,
  });

  if (currentDeals.length === 0) {
    return isPreview ? <EmptyRowHeading title={title} /> : null;
  }

  const hotDeals = currentDeals.map((deal) => ({ ...deal, isHotDeal: true as const }));

  return (
    <section>
      {/* Header: title + time-window toggle — mirrors SectionHeader layout */}
      <div className="mb-3 flex items-center justify-between px-6 pt-4">
        <h2 className="text-text-primary text-[length:var(--font-size-xl)] leading-[var(--line-height-tight)] font-[var(--font-weight-extrabold)]">
          {title}
        </h2>
        <div className="flex shrink-0 gap-1" role="group" aria-label={title}>
          {WINDOWS.map(({ key, labelKey }) => (
            <Button
              key={key}
              variant="ghost"
              size="sm"
              onClick={() => setActiveWindow(key)}
              aria-pressed={activeWindow === key}
              className={
                activeWindow === key
                  ? 'bg-surface-app text-content-primary'
                  : 'text-content-secondary hover:text-content-primary'
              }
            >
              {tFeed(labelKey)}
            </Button>
          ))}
        </div>
      </div>
      <ScrollRow gap="3" px="6" py="2" aria-label={title}>
        {hotDeals.map((deal, index) => (
          <DealCard
            key={deal.id}
            deal={deal}
            demo={demo}
            variant="scroll"
            aboveFold={index === 0}
            className="w-36 lg:w-48"
          />
        ))}
      </ScrollRow>
    </section>
  );
}
