import { useState } from 'react';
import { DetailedGame, UserProfile } from '../api/client';
import { FocusableItem } from './FocusableItem';
import { AchievementList } from './AchievementList';

interface GameDetailsPaneProps {
  game: DetailedGame;
  itemId: string;
  user?: UserProfile | null;
  activeMediaIndex: number;
  setActiveMediaIndex: (idx: number) => void;
  setActiveZone: (zone: string) => void;
  onPlay: (id: string) => void;
  onFavorite: (id: string, fav: boolean) => void;
  onOpenCollection: () => void;
  onOpenManual: () => void;
  mode: string;
}

export const GameDetailsPane = ({
  game,
  itemId,
  user,
  activeMediaIndex,
  setActiveMediaIndex,
  setActiveZone,
  onPlay,
  onFavorite,
  onOpenCollection,
  onOpenManual,
  mode
}: GameDetailsPaneProps) => {
  const [activeTab, setActiveTab] = useState<'saves' | 'states'>('saves');
  const [showOthers, setShowOthers] = useState(false);
  const saves = game.saves || [];
  const states = game.states || [];
  const notes = game.notes || [];

  const filteredNotes = notes.filter(note => {
    const isMine = user && note.username === user.username;
    if (showOthers) return true;
    return isMine;
  });

  const mediaItems: { type: 'video' | 'image', url: string, youtubeId?: string }[] = [];
  if (game.youtubeId) mediaItems.push({ type: 'video', url: '', youtubeId: game.youtubeId });
  else if (game.videoUrl) mediaItems.push({ type: 'video', url: game.videoUrl });
  if (game.screenshots) {
    game.screenshots.forEach(s => mediaItems.push({ type: 'image', url: s }));
  }

  const setFocusZone = () => { if (mode === 'gamepad') setActiveZone('details'); };

  return (
    <div className="pt-10 pl-10 pr-16 pb-16">
      <div className="flex gap-10 items-start h-[30rem]">
        {/* Poster */}
        <div className="w-[20rem] h-full rounded-2xl overflow-hidden shadow-[0_20px_50px_rgba(0,0,0,0.5)] border border-white/10 shrink-0 relative group">
          <img src={game.coverUrl} className="w-full h-full object-cover transition-transform duration-1000 group-hover:scale-110" alt="" />
          <div className="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent opacity-60"></div>
        </div>

        {/* Metadata Content */}
        <div className="flex-1 flex flex-col h-full min-w-0">
          <div className="flex items-center gap-3 mb-0 uppercase geist-mono font-black text-[0.625rem] tracking-widest">
            <div className="bg-[#2563eb] text-white px-3 py-1 rounded shadow-lg shadow-[#2563eb]/20">Playable</div>
            <div className="bg-white/10 text-white/60 px-3 py-1 rounded border border-white/5">{game.players || '1 Player'}</div>
          </div>
          <h1 className="text-[3.375rem] font-black text-white leading-[0.9] tracking-tighter uppercase mb-3 geist-mono truncate" title={game.title}>{game.title}</h1>
          <div className="border-t border-white/10 w-full mb-3"></div>
          
          <div className="space-y-2 mb-4 text-[0.6875rem] font-black tracking-[0.2em] geist-mono uppercase">
            <div className="flex items-center gap-10 overflow-hidden">
              <div className="flex gap-2 min-w-0 shrink-0"><span className="text-[#2563eb] w-[8.75rem] shrink-0">Region:</span> <span className="text-white truncate max-w-[12.5rem]">{game.regions?.join(', ') || 'N/A'}</span></div>
              <div className="flex gap-2 shrink-0"><span className="text-[#2563eb] shrink-0">Release date:</span> <span className="text-white">{game.releaseDate || 'N/A'}</span></div>
            </div>
            <div className="flex items-center gap-10 overflow-hidden">
              <div className="flex gap-2 min-w-0 shrink-0"><span className="text-[#2563eb] w-[8.75rem] shrink-0">Franchise:</span> <span className="text-white truncate max-w-[12.5rem]">{game.collections?.join(', ') || 'N/A'}</span></div>
              <div className="flex gap-2 min-w-0"><span className="text-[#2563eb] shrink-0">Companies:</span> <span className="text-white truncate font-bold text-ellipsis">{[...(game.developers || []), ...(game.publishers || [])].slice(0, 3).join(', ') || 'Unknown Company'}</span></div>
            </div>
            <div className="flex items-center gap-10 overflow-hidden">
              <div className="flex gap-2 min-w-0 shrink-0"><span className="text-[#2563eb] w-[8.75rem] shrink-0">Age Rating:</span> <span className="text-white">{game.esrbRating || 'NR'}</span></div>
              <div className="flex gap-2 min-w-0"><span className="text-[#2563eb] shrink-0">Genres:</span> <span className="text-white truncate">{game.genres?.slice(0, 4).join(', ') || 'N/A'}</span></div>
            </div>
          </div>

          <div className="bg-white/5 rounded-lg p-5 mb-8 flex-1 overflow-y-auto border border-white/5 scrollbar-hide">
            <p className="text-[0.9375rem] text-white/80 leading-[1.8] font-medium">{game.summary || 'No summary available for this entry.'}</p>
          </div>

          <div className="flex items-center gap-3">
            <FocusableItem onFocus={setFocusZone} onEnterPress={() => onPlay(itemId)} onClick={() => onPlay(itemId)} className="shrink-0" focusKey="DETAILS_PLAY">
              {(focused) => (<button className={`h-[3.375rem] px-8 rounded-xl font-black uppercase text-[0.75rem] tracking-[0.1em] flex items-center gap-3 transition-all duration-300 shadow-2xl ${focused ? 'bg-white text-black scale-110 ring-4 ring-[#2563eb] shadow-[0_0_25px_rgba(37,99,235,0.4)]' : 'bg-white text-black hover:scale-105'}`}><span className="material-symbols-outlined text-[1.5rem] filled" style={{ fontVariationSettings: "'FILL' 1" }}>play_arrow</span>Start Game</button>)}
            </FocusableItem>
            <FocusableItem onFocus={setFocusZone} className="shrink-0" focusKey="DETAILS_DOWNLOAD">
              {(focused) => (<button className={`h-[3.375rem] px-8 rounded-xl font-black uppercase text-[0.75rem] tracking-[0.1em] flex items-center gap-3 transition-all duration-300 border-2 ${focused ? 'scale-110 border-[#2563eb] bg-[#2563eb]/20 text-white ring-4 ring-[#2563eb]/20' : 'bg-white/5 border-white/10 text-white'}`}><span className="material-symbols-outlined text-[1.5rem]">download</span>Download</button>)}
            </FocusableItem>
            <div className="flex gap-3 ml-4">
              <FocusableItem onFocus={setFocusZone} onEnterPress={() => onFavorite(itemId, !game.favorite)} onClick={() => onFavorite(itemId, !game.favorite)} focusKey="DETAILS_FAVORITE">
                {(focused) => (
                  <button className={`w-[3.375rem] h-[3.375rem] flex items-center justify-center transition-all duration-300 rounded-xl border-2 ${focused ? 'scale-110 border-[#2563eb] bg-[#2563eb]/20 ring-4 ring-[#2563eb]/20 shadow-[0_0_15px_rgba(37,99,235,0.3)]' : 'bg-white/5 border-white/10'}`}>
                    <span className={`material-symbols-outlined text-[1.5rem] ${game.favorite ? 'filled text-[#2563eb]' : 'text-white/40'} ${focused ? '!text-white' : ''}`} style={game.favorite ? { fontVariationSettings: "'FILL' 1" } : {}}>star</span>
                  </button>
                )}
              </FocusableItem>
              <FocusableItem onFocus={setFocusZone} onEnterPress={onOpenCollection} onClick={onOpenCollection} focusKey="DETAILS_COLLECTION">
                {(focused) => (<button className={`w-[3.375rem] h-[3.375rem] flex items-center justify-center transition-all duration-300 rounded-xl border-2 ${focused ? 'scale-110 border-[#2563eb] text-white bg-[#2563eb]/20 ring-4 ring-[#2563eb]/20 shadow-[0_0_15px_rgba(37,99,235,0.3)]' : 'bg-white/5 border-white/10 text-white/40'}`}><span className="material-symbols-outlined text-[1.5rem]">library_add</span></button>)}
              </FocusableItem>
              <FocusableItem onFocus={setFocusZone} onEnterPress={onOpenManual} onClick={onOpenManual} focusKey="DETAILS_MANUAL">
                {(focused) => (<button className={`w-[3.375rem] h-[3.375rem] flex items-center justify-center transition-all duration-300 rounded-xl border-2 ${focused ? 'scale-110 border-[#2563eb] text-white bg-[#2563eb]/20 ring-4 ring-[#2563eb]/20 shadow-[0_0_15px_rgba(37,99,235,0.3)]' : 'bg-white/5 border-white/10 text-white/40'}`}><span className="material-symbols-outlined text-[1.5rem]">menu_book</span></button>)}
              </FocusableItem>
            </div>
          </div>
        </div>
      </div>

      {/* Media Galleria Container */}
      {mediaItems.length > 0 && (
        <div className="mt-12 grid grid-cols-12 gap-8 items-stretch">
          <div className="col-span-6 bg-white/5 rounded-xl p-5 border border-white/5 flex flex-col shadow-2xl h-[30rem] overflow-hidden">
            <div className="aspect-video w-full rounded-[0.625rem] bg-black/40 border border-white/10 overflow-hidden relative mb-5 group">
              {mediaItems[activeMediaIndex].type === 'video' ? (
                  mediaItems[activeMediaIndex].youtubeId ? (
                    <iframe src={`https://www.youtube.com/embed/${mediaItems[activeMediaIndex].youtubeId}?autoplay=0&controls=1&rel=0`} className="w-full h-full" allowFullScreen></iframe>
                  ) : (<video key={mediaItems[activeMediaIndex].url} src={mediaItems[activeMediaIndex].url} controls className="w-full h-full object-cover" />)
              ) : (<img src={mediaItems[activeMediaIndex].url} className="w-full h-full object-cover animate-fade-in" alt="" />)}
            </div>
            <div className="flex gap-3 overflow-x-auto pb-2 scrollbar-hide">
              {mediaItems.map((item, idx) => (
                <FocusableItem key={idx} onFocus={() => { setFocusZone(); setActiveMediaIndex(idx); }} onClick={() => setActiveMediaIndex(idx)} className="shrink-0" focusKey={`THUMB_${idx}`}>
                  {(focused) => (
                    <div className={`w-[7.75rem] aspect-video rounded-md border-2 transition-all duration-300 overflow-hidden relative ${focused || activeMediaIndex === idx ? 'border-[#2563eb] scale-105 z-10' : 'border-white/10 opacity-40 grayscale hover:opacity-100 hover:grayscale-0'}`}>
                      {item.type === 'video' ? (<div className="w-full h-full bg-black/60 flex items-center justify-center"><span className="material-symbols-outlined text-[#2563eb] text-3xl filled">play_circle</span></div>) : (<img src={item.url} className="w-full h-full object-cover" alt="" />)}
                    </div>
                  )}
                </FocusableItem>
              ))}
            </div>
          </div>
          <AchievementList raId={game.ra_id} achievements={game.merged_ra_metadata?.achievements} userProgression={user?.ra_progression} />
        </div>
      )}

      {/* How Long To Beat Container */}
      {game.hltb_metadata && (
        <div className="mt-8 w-full bg-white/5 rounded-2xl px-6 py-4 border border-white/5 shadow-2xl relative overflow-hidden text-white">
          <div className="flex items-center gap-2 mb-4 uppercase geist-mono font-black text-[0.75rem] tracking-widest text-white/30">
            <span className="material-symbols-outlined text-[1.125rem]">schedule</span>
            How Long To Beat
          </div>
          
          <div className="grid grid-cols-4 gap-4">
            {(() => {
              const formatTime = (seconds?: number) => {
                if (!seconds) return '--';
                const hours = seconds / 3600;
                if (hours >= 100) return `${Math.round(hours)}h`;
                const formatted = Math.round(hours * 10) / 10;
                return `${formatted}h`;
              };

              const StatItem = ({ title, seconds, count }: { title: string, seconds?: number, count?: number }) => (
                <div className="flex flex-col items-center justify-center text-center">
                  <div className="text-[0.625rem] font-bold text-white/30 uppercase tracking-[0.2em] mb-2 geist-mono">{title}</div>
                  <div className="text-[1.75rem] font-black text-white leading-none mb-2 geist-mono tracking-tighter">
                    {formatTime(seconds)}
                  </div>
                  <div className="text-[0.5625rem] font-medium text-white/20 uppercase tracking-widest geist-mono">
                    {count ? `${count} players` : 'Global Average'}
                  </div>
                </div>
              );

              return (
                <>
                  <StatItem title="Main Story" seconds={game.hltb_metadata.main_story} count={game.hltb_metadata.main_story_count} />
                  <StatItem title="Main + Extra" seconds={game.hltb_metadata.main_plus_extra} count={game.hltb_metadata.main_plus_extra_count} />
                  <StatItem title="Completionist" seconds={game.hltb_metadata.completionist} count={game.hltb_metadata.completionist_count} />
                  <StatItem title="All Styles" seconds={game.hltb_metadata.all_styles} count={game.hltb_metadata.all_styles_count} />
                </>
              );
            })()}
          </div>
        </div>
      )}

      {/* Saves, States and Notes Grid */}
      <div className="grid grid-cols-12 gap-8 mt-12 mb-12">
        {/* Tabbed Saves & States Section */}
        <div className="col-span-6 h-[30rem] bg-white/5 rounded-[12px] pt-1 px-5 pb-5 border border-white/5 flex flex-col overflow-hidden relative">
          <div className="flex items-center justify-between mb-1 px-2 h-10">
            <div className="flex items-center gap-6">
              <FocusableItem 
                onFocus={setFocusZone}
                onClick={() => setActiveTab('saves')} 
                onEnterPress={() => setActiveTab('saves')}
                focusKey="SAVES_TAB"
              >
                {(focused) => (
                  <button className={`geist-mono font-black text-[0.75rem] tracking-[0.2em] transition-all relative py-1 ${activeTab === 'saves' ? 'text-white' : 'text-white/30 hover:text-white/50'} ${focused ? 'scale-110 text-[#2563eb]' : ''}`}>
                    SAVES
                    {activeTab === 'saves' && <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#2563eb] shadow-[0_0_10px_rgba(37,99,235,0.5)]" />}
                  </button>
                )}
              </FocusableItem>
              <FocusableItem 
                onFocus={setFocusZone}
                onClick={() => setActiveTab('states')} 
                onEnterPress={() => setActiveTab('states')}
                focusKey="STATES_TAB"
              >
                {(focused) => (
                  <button className={`geist-mono font-black text-[0.75rem] tracking-[0.2em] transition-all relative py-1 ${activeTab === 'states' ? 'text-white' : 'text-white/30 hover:text-white/50'} ${focused ? 'scale-110 text-[#2563eb]' : ''}`}>
                    STATES
                    {activeTab === 'states' && <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#2563eb] shadow-[0_0_10px_rgba(37,99,235,0.5)]" />}
                  </button>
                )}
              </FocusableItem>
            </div>
            
            <div className="flex items-center gap-2">
              <FocusableItem onFocus={setFocusZone} focusKey="SAVES_UPLOAD">
                {(focused) => (
                  <button className={`w-10 h-10 flex items-center justify-center rounded-lg transition-all ${focused ? 'bg-[#2563eb]/20 text-[#2563eb] ring-1 ring-[#2563eb] scale-110 shadow-lg' : 'text-white/40 hover:text-white/60 hover:bg-white/5'}`}>
                    <span className="material-symbols-outlined text-[1.25rem]">cloud_upload</span>
                  </button>
                )}
              </FocusableItem>
              <FocusableItem onFocus={setFocusZone} focusKey="SAVES_DOWNLOAD">
                {(focused) => (
                  <button className={`w-10 h-10 flex items-center justify-center rounded-lg transition-all ${focused ? 'bg-[#2563eb]/20 text-[#2563eb] ring-1 ring-[#2563eb] scale-110 shadow-lg' : 'text-white/40 hover:text-white/60 hover:bg-white/5'}`}>
                    <span className="material-symbols-outlined text-[1.25rem]">download</span>
                  </button>
                )}
              </FocusableItem>
              <FocusableItem onFocus={setFocusZone} focusKey="SAVES_DELETE">
                {(focused) => (
                  <button className={`w-10 h-10 flex items-center justify-center rounded-lg transition-all ${focused ? 'bg-red-500/20 text-red-500 ring-1 ring-red-500 scale-110 shadow-lg' : 'text-white/40 hover:text-red-400 hover:bg-red-500/10'}`}>
                    <span className="material-symbols-outlined text-[1.25rem]">delete</span>
                  </button>
                )}
              </FocusableItem>
            </div>
          </div>

          <div className="border-t border-white/5 mb-6"></div>
          
          <div className="flex-1 overflow-y-auto scrollbar-hoverable pr-2">
            {activeTab === 'saves' ? (
              (saves.length === 0) ? (
                <div className="h-full flex flex-col items-center justify-center text-center opacity-20">
                  <span className="material-symbols-outlined text-5xl mb-4">cloud_off</span>
                  <p className="geist-mono uppercase text-[0.625rem] tracking-widest">No saves found</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {saves.map(save => (
                    <div key={save.id} className="group/item flex items-center justify-between p-4 bg-white/[0.02] rounded-xl border border-white/5 hover:bg-white/[0.05] transition-all">
                      <div className="flex items-center gap-4 overflow-hidden">
                        <span className="material-symbols-outlined text-white/30">draft</span>
                        <div className="overflow-hidden">
                          <div className="text-sm font-bold truncate text-white/80">{save.file_name}</div>
                          <div className="text-[0.625rem] geist-mono text-white/30 uppercase tracking-wider">
                            {save.emulator} • Slot {save.slot ?? 0}
                          </div>
                        </div>
                      </div>
                      <div className="text-[0.625rem] geist-mono text-white/20">
                        {(save.file_size_bytes / 1024).toFixed(1)} KB
                      </div>
                    </div>
                  ))}
                </div>
              )
            ) : (
              (states.length === 0) ? (
                <div className="h-full flex flex-col items-center justify-center text-center opacity-20">
                  <span className="material-symbols-outlined text-5xl mb-4">history</span>
                  <p className="geist-mono uppercase text-[0.625rem] tracking-widest">No states found</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {states.map(state => (
                    <div key={state.id} className="group/item flex items-center justify-between p-4 bg-white/[0.02] rounded-xl border border-white/5 hover:bg-white/[0.05] transition-all">
                      <div className="flex items-center gap-4 overflow-hidden">
                        <span className="material-symbols-outlined text-white/30">history</span>
                        <div className="overflow-hidden">
                          <div className="text-sm font-bold truncate text-white/80">{state.file_name}</div>
                          <div className="text-[0.625rem] geist-mono text-white/30 uppercase tracking-wider">
                            {state.emulator}
                          </div>
                        </div>
                      </div>
                      <div className="text-[0.625rem] geist-mono text-white/20">
                        {new Date(state.created_at).toLocaleDateString()}
                      </div>
                    </div>
                  ))}
                </div>
              )
            )}
          </div>
        </div>

        {/* Personal Notes Section */}
        <div className="col-span-6 h-[30rem] bg-white/5 rounded-[12px] pt-1 px-5 pb-5 border border-white/5 flex flex-col overflow-hidden relative">
          <div className="flex items-center justify-between mb-1 px-2 h-10">
            <div className="flex items-center gap-3 uppercase geist-mono font-black text-[0.75rem] tracking-[0.2em] text-white">
              <span className="material-symbols-outlined text-[1.25rem]">edit_note</span>
              {showOthers ? 'Global Notes' : 'Personal Notes'}
            </div>

            <div className="flex items-center gap-2">
              <FocusableItem 
                onFocus={setFocusZone} 
                onClick={() => setShowOthers(!showOthers)} 
                onEnterPress={() => setShowOthers(!showOthers)}
                focusKey="TOGGLE_PUBLIC_NOTES"
              >
                {(focused) => (
                  <button className={`w-10 h-10 flex items-center justify-center rounded-lg transition-all ${focused ? 'bg-[#2563eb]/20 text-[#2563eb] ring-1 ring-[#2563eb] scale-110 shadow-lg' : showOthers ? 'text-[#2563eb] bg-[#2563eb]/10' : 'text-white/40 hover:text-white/60 hover:bg-white/5'}`}>
                    <span className="material-symbols-outlined text-[1.25rem]">{showOthers ? 'public' : 'public_off'}</span>
                  </button>
                )}
              </FocusableItem>
              <FocusableItem onFocus={setFocusZone} focusKey="ADD_NOTE">
                {(focused) => (
                  <button className={`w-10 h-10 flex items-center justify-center rounded-lg transition-all ${focused ? 'bg-[#2563eb]/20 text-[#2563eb] ring-1 ring-[#2563eb] scale-110 shadow-lg' : 'text-white/40 hover:text-white/60 hover:bg-white/5'}`}>
                    <span className="material-symbols-outlined text-[1.25rem]">add</span>
                  </button>
                )}
              </FocusableItem>
            </div>
          </div>

          <div className="border-t border-white/5 mb-6"></div>

          <div className="flex-1 overflow-y-auto scrollbar-hoverable pr-2">
            {filteredNotes.length === 0 ? (
              <div className="h-full flex flex-col items-center justify-center text-center opacity-20">
                <span className="material-symbols-outlined text-5xl mb-4">{showOthers ? 'public_off' : 'note_stack'}</span>
                <p className="geist-mono uppercase text-[0.625rem] tracking-widest">{showOthers ? 'No public entries' : 'No entries recorded'}</p>
              </div>
            ) : (
              <div className="space-y-8">
                {filteredNotes.map(note => (
                  <div key={note.id} className="space-y-4">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="text-lg font-bold text-white/80 tracking-tight">{note.title}</div>
                        {note.username !== user?.username && (
                          <span className="px-2 py-0.5 bg-white/5 rounded text-[0.5rem] geist-mono text-white/30 uppercase tracking-widest border border-white/10">
                            {note.username}
                          </span>
                        )}
                      </div>
                      <div className="text-[0.625rem] geist-mono text-white/20 uppercase">
                        {new Date(note.updated_at).toLocaleDateString()}
                      </div>
                    </div>
                    <div className="text-sm leading-relaxed text-white/50 bg-white/[0.02] p-5 rounded-xl border border-white/5">
                      {note.content}
                    </div>
                    {note.tags && note.tags.length > 0 && (
                      <div className="flex flex-wrap gap-2">
                        {note.tags.map(tag => (
                          <span key={tag} className="px-2 py-0.5 bg-blue-500/10 border border-blue-500/20 rounded text-[0.625rem] geist-mono text-blue-400 uppercase tracking-widest">
                            {tag}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
