import { useState, useEffect } from 'react';
import { useFocusable, FocusContext, setFocus } from '@noriginmedia/norigin-spatial-navigation';
import { rommApiClient } from '../api/client';
import { EmulatorPlayer } from './EmulatorPlayer';
import { useQuery } from '@tanstack/react-query';

interface EmulatorOverlayProps {
  gameId: string;
  onClose: () => void;
}

const FocusableItem = ({ children, onClick, onEnterPress, focusKey, onFocus, className }: any) => {
  const { ref, focused } = useFocusable({
    onEnterPress,
    focusKey
  });

  useEffect(() => {
    if (focused && onFocus) onFocus();
  }, [focused]);

  return (
    <div ref={ref} onClick={onClick} className={className}>
      {children(focused)}
    </div>
  );
};

export const EmulatorOverlay = ({ gameId, onClose }: EmulatorOverlayProps) => {
  const { ref: overlayRef, focusKey: overlayFocusKey } = useFocusable({
    isFocusBoundary: true,
    focusKey: 'EMULATOR_OVERLAY'
  });

  const [gameState, setGameState] = useState<'config' | 'playing'>('config');
  const [selectedSaveId, setSelectedSaveId] = useState<number | undefined>();
  const [selectedStateId, setSelectedStateId] = useState<number | undefined>();

  const { data: game, isLoading } = useQuery({
    queryKey: ['gameDetails', gameId],
    queryFn: () => rommApiClient.fetchGameDetails(gameId)
  });

  useEffect(() => {
    if (gameState === 'config') {
      setFocus('START_SESSION_BTN');
    }
  }, [gameState]);

  if (isLoading || !game) {
    return (
      <div className="fixed inset-0 z-[200] bg-black/90 backdrop-blur-3xl flex items-center justify-center">
        <div className="text-center">
          <div className="material-symbols-outlined text-4xl text-[#2563eb] animate-spin mb-4">progress_activity</div>
          <div className="text-[0.625rem] geist-mono text-white/40 uppercase tracking-[0.3em]">Preparing Atelier Session...</div>
        </div>
      </div>
    );
  }

  const handleLaunch = () => {
    setGameState('playing');
  };

  return (
    <FocusContext.Provider value={overlayFocusKey}>
      <div ref={overlayRef} className="fixed inset-0 z-[200] bg-[#0a0c14] animate-in fade-in duration-500 overflow-hidden">
        {gameState === 'config' ? (
          <div className="h-full flex flex-col items-center justify-center p-20 relative">
            {/* Background Atmosphere */}
            <div className="absolute inset-0 overflow-hidden pointer-events-none">
              <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[60rem] h-[60rem] bg-[#2563eb]/5 rounded-full blur-[120px]" />
              <img src={game.coverUrl} className="absolute inset-0 w-full h-full object-cover opacity-5 blur-3xl scale-110" alt="" />
            </div>

            <div className="max-w-[80rem] w-full grid grid-cols-12 gap-16 relative z-10">
              {/* Left Side: Game Art & Meta */}
              <div className="col-span-4 flex flex-col items-center">
                <div className="w-[20rem] aspect-[3/4] rounded-2xl overflow-hidden shadow-[0_0_80px_rgba(0,0,0,0.5)] border border-white/10 mb-8 transform -rotate-2 hover:rotate-0 transition-transform duration-700">
                  <img src={game.coverUrl} className="w-full h-full object-cover" alt={game.title} />
                </div>
                <h1 className="text-3xl font-black text-white text-center mb-2 geist-mono uppercase tracking-tighter leading-none">
                  {game.title}
                </h1>
                <p className="text-[#2563eb] text-[0.625rem] font-black uppercase tracking-[0.4em] geist-mono mb-6">
                  {game.system}
                </p>
                
                <div className="flex flex-wrap justify-center gap-2 max-w-xs">
                   {game.genres?.slice(0, 3).map(g => (
                     <span key={g} className="px-3 py-1 bg-white/5 border border-white/5 rounded-full text-[0.5rem] font-black uppercase tracking-widest text-white/30 geist-mono whitespace-nowrap">{g}</span>
                   ))}
                </div>
              </div>

              {/* Right Side: Configuration */}
              <div className="col-span-8 flex flex-col justify-center">
                <div className="mb-12">
                  <h2 className="text-[0.75rem] font-black text-white/30 uppercase tracking-[0.4em] mb-6 geist-mono border-b border-white/5 pb-2">Archival Data Selection</h2>
                  
                  <div className="grid grid-cols-2 gap-8">
                    {/* Saves Column */}
                    <div>
                      <div className="text-[0.625rem] font-black text-[#2563eb] uppercase tracking-widest mb-4 geist-mono">Native Saves</div>
                      <div className="space-y-3 max-h-[12rem] overflow-y-auto pr-2 scrollbar-hoverable scrollbar-active">
                        {game.saves && game.saves.length > 0 ? game.saves.map(save => (
                          <FocusableItem key={save.id} onClick={() => setSelectedSaveId(save.id)} onEnterPress={() => setSelectedSaveId(save.id)}>
                            {(focused: boolean) => (
                              <div className={`p-3 rounded-xl border transition-all cursor-pointer ${selectedSaveId === save.id ? 'bg-[#2563eb]/20 border-[#2563eb] scale-105' : 'bg-white/5 border-white/5 hover:bg-white/10'} ${focused ? 'ring-2 ring-white/20' : ''}`}>
                                <div className="flex items-center gap-3">
                                  <span className="material-symbols-outlined text-[#2563eb] text-lg">save</span>
                                  <div className="flex-1 min-w-0">
                                    <div className="text-[0.625rem] font-bold text-white uppercase truncate">{save.file_name}</div>
                                    <div className="text-[0.5rem] text-white/40 geist-mono uppercase">{new Date(save.updated_at).toLocaleDateString()}</div>
                                  </div>
                                  {selectedSaveId === save.id && <div className="w-2 h-2 rounded-full bg-[#2563eb] shadow-[0_0_8px_#2563eb]" />}
                                </div>
                              </div>
                            )}
                          </FocusableItem>
                        )) : (
                          <div className="p-8 rounded-xl border border-dashed border-white/5 text-center">
                            <span className="material-symbols-outlined text-white/10 text-3xl mb-2">inbox</span>
                            <div className="text-[0.5rem] font-black text-white/20 uppercase tracking-[0.2em] geist-mono">No Local Saves</div>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* States Column */}
                    <div>
                      <div className="text-[0.625rem] font-black text-[#2563eb] uppercase tracking-widest mb-4 geist-mono">Instant States</div>
                      <div className="space-y-3 max-h-[12rem] overflow-y-auto pr-2 scrollbar-hoverable scrollbar-active">
                        {game.states && game.states.length > 0 ? game.states.map(state => (
                          <FocusableItem key={state.id} onClick={() => setSelectedStateId(state.id)} onEnterPress={() => setSelectedStateId(state.id)}>
                            {(focused: boolean) => (
                              <div className={`p-3 rounded-xl border transition-all cursor-pointer ${selectedStateId === state.id ? 'bg-[#2563eb]/20 border-[#2563eb] scale-105' : 'bg-white/5 border-white/5 hover:bg-white/10'} ${focused ? 'ring-2 ring-white/20' : ''}`}>
                                <div className="flex items-center gap-3">
                                  <span className="material-symbols-outlined text-[#2563eb] text-lg">history</span>
                                  <div className="flex-1 min-w-0">
                                    <div className="text-[0.625rem] font-bold text-white uppercase truncate">{state.file_name}</div>
                                    <div className="text-[0.5rem] text-white/40 geist-mono uppercase">{new Date(state.updated_at).toLocaleDateString()}</div>
                                  </div>
                                  {selectedStateId === state.id && <div className="w-2 h-2 rounded-full bg-[#2563eb] shadow-[0_0_8px_#2563eb]" />}
                                </div>
                              </div>
                            )}
                          </FocusableItem>
                        )) : (
                          <div className="p-8 rounded-xl border border-dashed border-white/5 text-center">
                            <span className="material-symbols-outlined text-white/10 text-3xl mb-2">timer</span>
                            <div className="text-[0.5rem] font-black text-white/20 uppercase tracking-[0.2em] geist-mono">No Cached States</div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                {/* Launch Controls */}
                <div className="flex items-center gap-6 mt-4">
                  <FocusableItem focusKey="START_SESSION_BTN" onEnterPress={handleLaunch} onClick={handleLaunch}>
                    {(focused: boolean) => (
                      <button className={`px-12 h-16 rounded-2xl font-black text-[0.875rem] uppercase tracking-[0.4em] geist-mono transition-all flex items-center gap-4 ${focused ? 'bg-[#2563eb] text-white scale-110 shadow-[0_0_40px_rgba(37,99,235,0.4)] ring-4 ring-white/20' : 'bg-white text-black'}`}>
                        <span className="material-symbols-outlined filled" style={{ fontVariationSettings: "'FILL' 1" }}>play_arrow</span>
                        Start Session
                      </button>
                    )}
                  </FocusableItem>
                  <FocusableItem focusKey="CANCEL_SESSION_BTN" onEnterPress={onClose} onClick={onClose}>
                    {(focused: boolean) => (
                      <button className={`px-8 h-16 rounded-2xl font-black text-[0.75rem] uppercase tracking-[0.2em] geist-mono transition-all border ${focused ? 'bg-white/10 border-white text-white' : 'bg-transparent border-white/10 text-white/30'}`}>
                        Abort
                      </button>
                    )}
                  </FocusableItem>
                </div>
              </div>
            </div>

            {/* Hint bar */}
            <div className="absolute bottom-12 left-12 flex items-center gap-8">
               <div className="flex items-center gap-3">
                 <div className="w-6 h-6 rounded flex items-center justify-center bg-white/10 text-[10px] font-bold text-white/50 border border-white/5">ENTER</div>
                 <div className="text-[0.625rem] font-black text-white/20 uppercase tracking-widest">Select Data</div>
               </div>
               <div className="flex items-center gap-3">
                 <div className="w-6 h-6 rounded flex items-center justify-center bg-white/10 text-[10px] font-bold text-white/50 border border-white/5">ESC</div>
                 <div className="text-[0.625rem] font-black text-white/20 uppercase tracking-widest">Back to Archives</div>
               </div>
            </div>
          </div>
        ) : (
          (() => {
            const platformSlug = game.system.toLowerCase().replace(/\s+/g, '-');
            const defaultExt = ['nds', 'nintendo-ds'].includes(platformSlug) ? 'nds' 
              : ['psx', 'playstation', 'saturn', '3do', 'sega-cd'].includes(platformSlug) ? 'chd' 
              : 'zip';
            const ext = game.fsName ? game.fsName.split('.').pop() : defaultExt;
            
            return (
              <EmulatorPlayer 
                romId={gameId} 
                romUrl={rommApiClient.getRomFileUrl(gameId, `game.${ext}`)}
                platformSlug={platformSlug} 
                saveId={selectedSaveId}
                stateId={selectedStateId}
                onClose={onClose}
              />
            );
          })()
        )}
      </div>
    </FocusContext.Provider>
  );
};
