import { useState, useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { GameListItem } from './GameListItem';
import { GameDetailsPane } from './GameDetailsPane';
import { AlphabetScroller } from './AlphabetScroller';
import { AtelierExplorer } from './AtelierExplorer';
import { CollectionHeaderItem } from './CollectionHeaderItem';
import { CollectionModal } from './CollectionModal';
import { ManualModal } from './ManualModal';
import { EmulatorOverlay } from './EmulatorOverlay';
import { rommApiClient } from '../api/client';
import { useInputMode } from '../context/InputModeContext';

export const CollectionsPage = () => {
  const { mode } = useInputMode();
  const { collectionId, romId } = useParams();
  const queryClient = useQueryClient();

  const [activeMediaIndex, setActiveMediaIndex] = useState(0);
  const [playingGameId, setPlayingGameId] = useState<string | null>(null);
  const [isCollectionModalOpen, setIsCollectionModalOpen] = useState(false);
  const [isManualModalOpen, setIsManualModalOpen] = useState(false);

  const collectionsQuery = useQuery({ 
    queryKey: ['collections'], 
    queryFn: () => rommApiClient.fetchCollections() 
  });

  const activeCollectionId = collectionId || '';
  const activeCollection = collectionsQuery.data?.find(c => String(c.id) === String(activeCollectionId));

  const detailsQuery = useQuery({
    queryKey: ['gameDetails', romId],
    queryFn: () => rommApiClient.fetchGameDetails(romId!),
    enabled: !!romId,
    staleTime: 1000 * 60 * 5,
  });

  const userQuery = useQuery({ 
    queryKey: ['currentUser'], 
    queryFn: () => rommApiClient.fetchCurrentUser() 
  });

  const favoriteMutation = useMutation({
    mutationFn: ({ gameId, favorite }: { gameId: string, favorite: boolean }) => 
      rommApiClient.toggleFavorite(gameId, favorite),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['gameDetails', romId] });
      queryClient.invalidateQueries({ queryKey: ['collections'] });
    }
  });

  const activeLetters = useMemo(() => {
    if (!activeCollection?.games) return [];
    const letters = new Set<string>();
    activeCollection.games.forEach(game => {
      const firstChar = (game.title || '').charAt(0).toUpperCase();
      if (/[A-Z]/.test(firstChar)) letters.add(firstChar);
      else letters.add('#');
    });
    return Array.from(letters).sort();
  }, [activeCollection]);

  return (
    <AtelierExplorer
      categoryName="COLLECTION"
      categoryRoute="collections"
      categories={(collectionsQuery.data || []).map(c => ({ id: c.id, name: c.name }))}
      items={activeCollection?.games || []}
      isLoadingCategories={collectionsQuery.isLoading}
      isLoadingItems={collectionsQuery.isLoading}
      renderCategory={(c, active, onSelect) => {
        const fullCol = collectionsQuery.data?.find(col => String(col.id) === String(c.id));
        if (!fullCol) return null;
        return <CollectionHeaderItem key={c.id} collection={fullCol} active={active} onSelect={onSelect} />;
      }}
      renderListItem={(game, active, onFocus) => (
        <GameListItem key={game.id} game={game} active={active} onFocus={onFocus} />
      )}
      alphabet={activeLetters.length > 0 && (
        <AlphabetScroller letters={activeLetters} onLetterPress={() => {}} />
      )}
      renderDetails={(itemId, activeZone, setActiveZone) => (
        detailsQuery.data ? (
          <GameDetailsPane 
            game={detailsQuery.data}
            itemId={itemId}
            user={userQuery.data}
            activeMediaIndex={activeMediaIndex}
            setActiveMediaIndex={setActiveMediaIndex}
            activeZone={activeZone}
            setActiveZone={setActiveZone}
            onPlay={setPlayingGameId}
            onFavorite={(id, fav) => favoriteMutation.mutate({ gameId: id, favorite: fav })}
            onOpenCollection={() => setIsCollectionModalOpen(true)}
            onOpenManual={() => setIsManualModalOpen(true)}
            mode={mode}
          />
        ) : (
          <div className="h-full flex items-center justify-center"><div className="text-center"><div className="material-symbols-outlined text-4xl text-white/10 animate-spin mb-4">progress_activity</div><div className="text-[0.625rem] geist-mono text-white/20 uppercase tracking-widest">Hydrating Metadata...</div></div></div>
        )
      )}
      overlays={
        <>
          {isCollectionModalOpen && detailsQuery.data && (
            <CollectionModal
              collections={collectionsQuery.data || []}
              onClose={() => setIsCollectionModalOpen(false)}
              onSelect={() => {}}
              onCreate={() => {}}
            />
          )}
          {playingGameId && <EmulatorOverlay gameId={playingGameId} onClose={() => setPlayingGameId(null)} />}
          {isManualModalOpen && detailsQuery.data && (
            <ManualModal gameId={detailsQuery.data.id} platformId={detailsQuery.data.platformId} onClose={() => setIsManualModalOpen(false)} />
          )}
        </>
      }
    />
  );
};
