'use client';

import { useState, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useT } from '@/lib/i18n/react';
import { Container } from '@/components/ui/layout/Container';
import { HydratedIsland } from '@/components/HydratedIsland';
import { AppShell } from '@/components/ui/layout/AppShell';
import { BottomNav, useCustomerNavItems } from '@/components/ui/layout/BottomNav';
import { SiteNav } from '@/components/ui/layout/SiteNav';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import { Button } from '@/components/ui/primitives/Button';
import { Icon } from '@/components/ui/icons/Icon';
import { GlobalCartDrawer } from '@/components/ui/domain/cart/GlobalCartDrawer';
import { DealCard } from '@/components/ui/domain/DealCard/DealCard';
import { AmbientDealCard } from '@/features/deals/AmbientDealCard';
import { CheckoutModal } from '@/features/checkout-modal/CheckoutModal';
import { getAnonRecentlyViewed, clearAnonRecentlyViewed } from './anonRecentlyViewedStore.js';
import { getCsrfToken } from '@/lib/csrf';
import { captureCaught } from '@/lib/observability';
import type { RecentlyViewedDeal } from '@/server/db/queries/recently-viewed.js';
import type { Locale } from '@/lib/i18n';

export interface RecentlyViewedPageProps {
  locale: Locale;
  isGuest: boolean;
  isAdmin?: boolean;
  isVendor?: boolean;
  initialItems?: RecentlyViewedDeal[];
}

function RecentlyViewedPageInner({
  isGuest,
  isAdmin = false,
  isVendor = false,
  initialItems = [],
}: Omit<RecentlyViewedPageProps, 'locale'>) {
  const t = useT('recently_viewed');
  const qc = useQueryClient();

  const [items, setItems] = useState<RecentlyViewedDeal[]>(initialItems);
  const [hydrated, setHydrated] = useState(!isGuest);
  const [clearError, setClearError] = useState(false);

  useEffect(() => {
    if (!isGuest) return;
    const stored = getAnonRecentlyViewed();
    if (stored.length === 0) {
      void Promise.resolve().then(() => setHydrated(true));
      return;
    }
    void fetch('/api/deals/batch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ dealIds: stored.map((x) => x.dealId) }),
    })
      .then(
        (res) =>
          res.json() as Promise<{ ok: boolean; deals: Omit<RecentlyViewedDeal, 'viewedAt'>[] }>,
      )
      .then(({ deals }) => {
        const withViewedAt: RecentlyViewedDeal[] = deals.map((d) => {
          const found = stored.find((s) => s.dealId === d.id);
          return { ...d, viewedAt: new Date(found?.viewedAt ?? 0).toISOString() };
        });
        withViewedAt.sort(
          (a, b) => new Date(b.viewedAt).getTime() - new Date(a.viewedAt).getTime(),
        );
        setItems(withViewedAt);
      })
      .catch((err: unknown) => {
        captureCaught(err, {
          scope: 'features.recently-viewed.RecentlyViewedPage',
          severity: 'warning',
        });
      })
      .finally(() => setHydrated(true));
  }, [isGuest]);

  const clearMutation = useMutation({
    mutationFn: async () => {
      if (isGuest) {
        clearAnonRecentlyViewed();
        return;
      }
      const res = await fetch('/api/me/recently-viewed', {
        method: 'DELETE',
        credentials: 'include',
        headers: { 'x-csrf-token': getCsrfToken() },
      });
      if (!res.ok) throw new Error('clear failed');
    },
    onSuccess: () => {
      setClearError(false);
      setItems([]);
      void qc.invalidateQueries({ queryKey: ['recently-viewed'] });
    },
    onError: () => setClearError(true),
  });

  const navItems = useCustomerNavItems('/recently-viewed');

  return (
    <AppShell
      mode="customer"
      topBar={
        <SiteNav
          variant="mobile"
          title={t('title')}
          currentPath="/recently-viewed"
          isGuest={isGuest}
          isAdmin={isAdmin}
          isVendor={isVendor}
        />
      }
      desktopTopBar={
        <SiteNav
          variant="desktop"
          currentPath="/recently-viewed"
          isGuest={isGuest}
          isAdmin={isAdmin}
          isVendor={isVendor}
        />
      }
      bottomNav={<BottomNav mode="customer" items={navItems} />}
      pageOverlays={
        <>
          <GlobalCartDrawer />
          <CheckoutModal />
        </>
      }
    >
      <Container maxWidth="4xl" px="6">
        <main id="main" className="mx-auto max-w-4xl py-6">
          <h1 className="text-text-primary mb-6 text-2xl font-bold">{t('title')}</h1>

          {isGuest && (
            <div className="mb-6">
              <InlineNotice
                tone="info"
                description={t('guest_banner')}
                icon={
                  <a href="/login" className="font-semibold underline">
                    {t('guest_cta')}
                  </a>
                }
              />
            </div>
          )}

          {clearError && (
            <div role="alert" className="mb-4">
              <InlineNotice tone="danger" description={t('clear_error')} />
            </div>
          )}

          {hydrated && items.length > 0 && (
            <div className="mb-4 flex justify-end">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => clearMutation.mutate()}
                disabled={clearMutation.isPending}
              >
                <Icon name="Trash2" size="sm" className="me-1" />
                {t('clear')}
              </Button>
            </div>
          )}

          {hydrated && items.length === 0 ? (
            <EmptyState
              title={t('empty_title')}
              action={
                <Button asChild variant="primary" size="md">
                  <a href="/">{t('empty_cta')}</a>
                </Button>
              }
            />
          ) : (
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {items.map((deal) => (
                <AmbientDealCard key={deal.id} imageSrc={deal.imageSrc}>
                  <DealCard deal={{ ...deal, vendorAvatarUrl: deal.vendorAvatarUrl ?? undefined }} />
                </AmbientDealCard>
              ))}
            </div>
          )}
        </main>
      </Container>
    </AppShell>
  );
}

export function RecentlyViewedPage(props: RecentlyViewedPageProps) {
  return (
    <HydratedIsland locale={props.locale}>
      <RecentlyViewedPageInner {...props} />
    </HydratedIsland>
  );
}
