import LoaderIcon from '@/components/icons/loader-icon';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import MarketGridCard, {
  MarketGridCardSkeleton,
} from '@/components/user/dashboard/market-grid-card';
import fetcher from '@/lib/fetcher';
import { TMarket } from '@/types/market.types';
import { router } from '@inertiajs/react';
import { CaretRightIcon } from '@phosphor-icons/react';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import useSWRInfinite from 'swr/infinite';

const LIMIT = 8;

export type TrendingMarketsProps = {
  title: string;
};

export default function TrendingMarketsSection({
  title,
}: TrendingMarketsProps) {
  const { t } = useTranslation();

  // Paginated, trending-sorted open markets. `null` key stops fetching once a
  // short (last) page comes back.
  const getKey = (
    pageIndex: number,
    previous: { data: TMarket[] } | null,
  ): string | null => {
    if (previous && (previous.data?.length ?? 0) < LIMIT) return null;
    return `/api/markets?filter[status]=open&sort=-total_volume&limit=${LIMIT}&page=${pageIndex + 1}`;
  };

  const {
    data: pages,
    isLoading,
    isValidating,
    size,
    setSize,
  } = useSWRInfinite<{ data: TMarket[] }>(getKey, fetcher, {
    revalidateFirstPage: false,
  });

  const markets: TMarket[] = pages?.flatMap((p) => p?.data ?? []) ?? [];
  const hasMore = (pages?.[pages.length - 1]?.data?.length ?? 0) >= LIMIT;
  const isLoadingMore = isValidating && size > 1;

  // Auto-load the next page when the sentinel scrolls into view.
  const sentinelRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const el = sentinelRef.current;
    if (!el || !hasMore) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !isValidating) {
          setSize((s) => s + 1);
        }
      },
      { rootMargin: '200px' },
    );
    observer.observe(el);

    return () => observer.disconnect();
  }, [hasMore, isValidating, setSize]);

  return (
    <div className="container px-4 py-6">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-xl font-semibold text-card-foreground">{title}</h2>
        <Button
          variant="outline"
          onClick={() => router.visit('/markets')}
          className="rounded-full border-2 border-black/10 dark:border-white/10 dark:text-white/90 dark:hover:border-white/20"
        >
          {t('View all')}
          <div>
            <CaretRightIcon weight="bold" className="size-4" />
          </div>
        </Button>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {Array.from({ length: LIMIT }).map((_, i) => (
            <MarketGridCardSkeleton key={i} />
          ))}
        </div>
      ) : markets.length > 0 ? (
        <>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {markets.map((market) => (
              <MarketGridCard key={market.id} market={market} />
            ))}
          </div>

          {hasMore && (
            <div
              ref={sentinelRef}
              className="mt-6 flex h-10 items-center justify-center"
            >
              {isLoadingMore && <LoaderIcon />}
            </div>
          )}
        </>
      ) : (
        <Card className="rounded-2xl border border-dashed border-black/10 py-16 text-center text-sm text-black/40 dark:border-white/10 dark:text-white/40">
          {t('No open markets right now.')}
        </Card>
      )}
    </div>
  );
}
