'use client';

import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useQuery } from '@tanstack/react-query';
import { Tag } from 'lucide-react';

import { promotionsApi } from '@/lib/api';
import { useAuth } from '@/components/auth/AuthProvider';
import { SkeletonCard } from '@/components/ui/skeleton';
import { ErrorState } from '@/components/ui/error-state';
import { EmptyState } from '@/components/ui/empty-state';
import { ActiveOfferCard } from '@/components/offers/ActiveOfferCard';
import type { ActivePromotionsResponse } from '@/types/api';

export default function OffersPage() {
  const t = useTranslations('offers');
  const params = useParams<{ locale: string }>();
  const locale = params?.locale ?? 'en';
  const { status } = useAuth();

  // C4 — the active-promotions endpoint is auth-only. Gate guests with a sign-in
  // CTA instead of firing the request and surfacing a generic error.
  const { data, isPending, isError, refetch } = useQuery<ActivePromotionsResponse>({
    queryKey: ['promotions', 'active', locale],
    queryFn: () => promotionsApi.listActive(locale, { limit: 24 }),
    staleTime: 60_000,
    enabled: status === 'authenticated',
  });

  const offers = data?.data ?? [];
  const loginHref = `/${locale}/auth/login?next=${encodeURIComponent(`/${locale}/offers`)}`;

  return (
    <div className="mx-auto max-w-7xl px-4 py-8 md:py-12">
      <header className="mb-6">
        <h1 className="font-heading text-2xl font-bold text-neutral-900 md:text-3xl">{t('index.title')}</h1>
        <p className="mt-2 text-neutral-600">{t('index.subtitle')}</p>
      </header>

      {status === 'guest' ? (
        <EmptyState
          icon={<Tag className="h-6 w-6" aria-hidden />}
          heading={t('index.guest_title')}
          body={t('index.guest_body')}
          action={{ label: t('sign_in'), href: loginHref }}
        />
      ) : isPending ? (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-busy="true" aria-label={t('loading')}>
          <SkeletonCard />
          <SkeletonCard />
          <SkeletonCard />
        </div>
      ) : isError ? (
        <ErrorState body={t('error')} onRetry={() => refetch()} retryLabel={t('retry')} />
      ) : offers.length === 0 ? (
        <EmptyState icon={<Tag className="h-6 w-6" aria-hidden />} heading={t('empty')} />
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {offers.map((promo) => (
            <ActiveOfferCard
              key={promo.public_id}
              promo={promo}
              locale={locale}
              onExpire={() => refetch()}
            />
          ))}
        </div>
      )}
    </div>
  );
}
