'use client';

import { useMemo, useState } from 'react';
import { SectionHeader } from '@/components/ui/layout/SectionHeader';
import { ScrollRow } from '@/components/ui/layout/ScrollRow';
import { DealCard, type DealCardDeal } from '@/components/ui/domain/DealCard';
import { CitySelector } from '@/features/near-you/CitySelector';
import { UseMyLocationButton } from '@/components/ui/domain/UseMyLocationButton';
import { useLocale, useT } from '@/lib/i18n/react';
import { useFeedQuery, type UseFeedQueryOpts } from '@/lib/hooks/useFeedQuery';
import { useCityPreference } from '@/lib/hooks/useCityPreference';
import type { FeedFilter } from '@/server/schemas/feed';
import type { FeedResult } from '@/server/db/queries/feed';
import type { Config } from './config';
import { EmptyRowHeading, useShouldRenderEmptyRow } from '../_shared/EmptyRowHeading';

export function Component({
  config,
  data,
  demo,
}: {
  config: Config;
  data: unknown;
  demo?: boolean;
}) {
  const { locale } = useLocale();
  const t = useT('near_you');
  const initial = (data ?? []) as DealCardDeal[];
  const { cityCode, radius, choose, setRadius } = useCityPreference();

  const filter = useMemo<FeedFilter>(
    () =>
      radius
        ? {
            radius,
            preset: 'near-you',
            limit: config.limit,
            hours: { mode: 'any' },
          }
        : {
            cityCode: cityCode ?? undefined,
            preset: 'near-you',
            limit: config.limit,
            hours: { mode: 'any' },
          },
    [cityCode, radius, config.limit],
  );

  // Seed query cache with SSR data so the first render does not fire /api/feed.
  // staleTime=60s + initialDataUpdatedAt=mountedAt suppresses the redundant mount fetch.
  // City/radius changes generate a new queryKey → triggers a real fetch automatically.
  const [feedOpts] = useState<UseFeedQueryOpts>(() =>
    initial.length > 0
      ? {
          initialData: {
            deals: initial,
            nextCursor: null,
            total: initial.length,
            center: null,
          } satisfies FeedResult,
          initialDataUpdatedAt: Date.now(),
        }
      : {},
  );

  // Only query when user has set an explicit location (city or geolocation).
  // Without a location, staleTime expiry would refetch with no geo filter → all deals.
  // SSR initialData (geo-IP based) is kept frozen until the user picks a location.
  //
  // feedOpts (initialData) must NOT be spread into enabled queries: when a new city is
  // picked the queryKey changes, and TanStack would pre-populate it with the SSR city's
  // initialData + a recent initialDataUpdatedAt, marking it fresh → no fetch fires.
  // Only seed the disabled (no-location) query so SSR data renders on first paint.
  const queryEnabled = !!(cityCode || radius);
  const { data: live } = useFeedQuery(filter, {
    ...(queryEnabled ? {} : feedOpts),
    enabled: queryEnabled,
  });
  const deals = live?.deals ?? initial;

  const title = config.title[locale];
  const isPreview = useShouldRenderEmptyRow();
  if (deals.length === 0) return isPreview ? <EmptyRowHeading title={title} /> : null;

  return (
    <section>
      <SectionHeader
        title={title}
        subtitle={undefined}
        actionHref="/near-you"
        actionLabel={t('seeAll')}
        extraStart={
          <div className="flex items-center gap-2">
            <CitySelector value={cityCode} onChange={choose} compact />
            <UseMyLocationButton onCoords={(lat, lng) => setRadius({ lat, lng, km: 5 })} iconOnly />
          </div>
        }
      />
      <ScrollRow gap="3" px="6" py="2" aria-label={title}>
        {deals.map((deal, index) => (
          <DealCard
            key={deal.id}
            deal={deal}
            demo={demo}
            variant="scroll"
            aboveFold={index === 0}
            className="w-36 lg:w-48"
          />
        ))}
      </ScrollRow>
    </section>
  );
}
