import React, { useState, useEffect } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';

import { rommApiClient } from '../api/client';

// Worker setup using CDN for maximum compatibility
pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

interface ManualModalProps {
  gameId: string;
  platformId?: number;
  onClose: () => void;
}

const FocusableControl = ({ 
  onFocus, 
  onEnterPress, 
  onClick, 
  children, 
  className, 
  focusKey 
}: { 
  onFocus: () => void; 
  onEnterPress?: () => void; 
  onClick?: () => void;
  children: (focused: boolean) => React.ReactNode; 
  className?: string;
  focusKey?: string;
}) => {
  const { ref, focused } = useFocusable({
    onFocus,
    onEnterPress,
    focusKey
  });

  return (
    <div 
      ref={ref} 
      className={`${className} ${focused ? 'focused' : ''}`}
      onClick={onClick}
    >
      {children(focused)}
    </div>
  );
};

export const ManualModal = ({ gameId, platformId, onClose }: ManualModalProps) => {
  const url = rommApiClient.getManualUrl(gameId, platformId);
  const [numPages, setNumPages] = useState<number | null>(null);
  const [pageNumber, setPageNumber] = useState(1);
  const [scale, setScale] = useState(1.0);
  const [error, setError] = useState<string | null>(null);

  const { ref, focusKey } = useFocusable({
    focusKey: 'MANUAL_MODAL',
    isFocusBoundary: true,
    autoRestoreFocus: true
  });

  const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
    setNumPages(numPages);
    setPageNumber(1);
    setError(null);
  };

  const onDocumentLoadError = (err: Error) => {
    console.error('PDF Load Error:', err);
    setError('Failed to load manual. The archive might be inaccessible or corrupted.');
  };

  const changePage = (offset: number) => {
    setPageNumber(prevPageNumber => {
      const next = prevPageNumber + offset;
      if (numPages && next >= 1 && next <= numPages) {
        return next;
      }
      return prevPageNumber;
    });
  };

  const changeScale = (delta: number) => {
    setScale(prev => Math.min(Math.max(prev + delta, 0.5), 3.0));
  };

  // Keyboard/Gamepad shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft' || e.key === 'PageUp') changePage(-1);
      if (e.key === 'ArrowRight' || e.key === 'PageDown') changePage(1);
    };

    const handleGamepadButton = (e: Event) => {
      const { button } = (e as CustomEvent<{ button: string }>).detail;
      if (button === 'B') onClose();
      if (button === 'LB') changePage(-1);
      if (button === 'RB') changePage(1);
      if (button === 'Up') changeScale(0.1);
      if (button === 'Down') changeScale(-0.1);
    };

    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('gamepadbutton', handleGamepadButton);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('gamepadbutton', handleGamepadButton);
    };
  }, [numPages, onClose]);

  return (
    <FocusContext.Provider value={focusKey}>
      <div 
        ref={ref}
        className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-8 backdrop-blur-xl animate-in fade-in duration-500"
      >
        {/* Header / Background branding */}
        <div className="absolute top-10 left-10 opacity-20 user-select-none pointer-events-none">
          <div className="text-4xl font-black geist-mono text-[#2563eb] tracking-tighter uppercase leading-none">
            Digital Archive<br />Technical Manual
          </div>
        </div>

        {/* PDF Container */}
        <div className="flex-1 w-full max-w-5xl overflow-auto scrollbar-hide flex justify-center items-start rounded-xl border border-white/10 bg-black/40 shadow-2xl relative shadow-black/80">
          {error ? (
            <div className="h-full flex flex-col items-center justify-center text-center p-20">
              <span className="material-symbols-outlined text-6xl text-red-500/50 mb-6">error</span>
              <p className="text-white/60 font-medium text-lg max-w-md leading-relaxed">{error}</p>
              <FocusableControl onFocus={() => {}} onEnterPress={onClose} onClick={onClose} className="mt-8">
                {(focused) => (
                  <button className={`px-10 py-4 rounded-full font-black uppercase text-[12px] tracking-widest transition-all ${focused ? 'bg-white text-black scale-110' : 'bg-white/10 text-white hover:bg-white/20'}`}>
                    Return to Library
                  </button>
                )}
              </FocusableControl>
            </div>
          ) : (
            <Document
              file={url}
              onLoadSuccess={onDocumentLoadSuccess}
              onLoadError={onDocumentLoadError}
              loading={
                <div className="h-full flex flex-col items-center justify-center">
                  <div className="material-symbols-outlined text-4xl text-[#2563eb] animate-spin mb-4">progress_activity</div>
                  <div className="text-[10px] geist-mono text-white/40 uppercase tracking-widest">Parsing Archive...</div>
                </div>
              }
            >
              <Page 
                pageNumber={pageNumber} 
                scale={scale} 
                renderTextLayer={true} 
                renderAnnotationLayer={true}
                className="shadow-[0_0_50px_rgba(0,0,0,0.8)]"
              />
            </Document>
          )}

          {/* Page Info Overlay */}
          {!error && numPages && (
            <div className="absolute top-6 right-6 px-4 py-2 bg-black/60 backdrop-blur-md rounded-lg border border-white/10 text-[10px] geist-mono font-black text-white/60 uppercase tracking-widest flex items-center gap-4">
               <div>Page <span className="text-white text-sm">{pageNumber}</span> / <span className="text-white/40">{numPages}</span></div>
               <div className="w-px h-3 bg-white/10"></div>
               <div>Zoom <span className="text-white text-sm">{Math.round(scale * 100)}%</span></div>
            </div>
          )}
        </div>

        {/* Control Bar */}
        <div className="shrink-0 mt-8 mb-4 flex items-center gap-4">
          <div className="flex bg-black/40 backdrop-blur-md p-1 rounded-2xl border border-white/10">
            <FocusableControl 
              onFocus={() => {}} 
              onEnterPress={() => changePage(-1)}
              onClick={() => changePage(-1)}
              focusKey="MANUAL_PREV"
            >
              {(focused) => (
                <button 
                  className={`w-[64px] h-[64px] flex items-center justify-center transition-all rounded-xl ${focused ? 'bg-[#2563eb] text-white scale-110 shadow-lg shadow-[#2563eb]/30' : 'text-white/30 hover:text-white/70'}`}
                  disabled={pageNumber <= 1}
                >
                  <span className="material-symbols-outlined text-[32px]">navigate_before</span>
                </button>
              )}
            </FocusableControl>

            <FocusableControl 
              onFocus={() => {}} 
              onEnterPress={() => changeScale(-0.2)}
              onClick={() => changeScale(-0.2)}
              focusKey="MANUAL_ZOUT"
            >
              {(focused) => (
                <button className={`w-[64px] h-[64px] flex items-center justify-center transition-all rounded-xl ${focused ? 'bg-[#2563eb] text-white scale-110 shadow-lg shadow-[#2563eb]/30' : 'text-white/30 hover:text-white/70'}`}>
                  <span className="material-symbols-outlined text-[32px]">zoom_out</span>
                </button>
              )}
            </FocusableControl>

            <FocusableControl 
              onFocus={() => {}} 
              onEnterPress={() => changeScale(0.2)}
              onClick={() => changeScale(0.2)}
              focusKey="MANUAL_ZIN"
            >
              {(focused) => (
                <button className={`w-[64px] h-[64px] flex items-center justify-center transition-all rounded-xl ${focused ? 'bg-[#2563eb] text-white scale-110 shadow-lg shadow-[#2563eb]/30' : 'text-white/30 hover:text-white/70'}`}>
                  <span className="material-symbols-outlined text-[32px]">zoom_in</span>
                </button>
              )}
            </FocusableControl>

            <FocusableControl 
              onFocus={() => {}} 
              onEnterPress={() => changePage(1)}
              onClick={() => changePage(1)}
              focusKey="MANUAL_NEXT"
            >
              {(focused) => (
                <button 
                  className={`w-[64px] h-[64px] flex items-center justify-center transition-all rounded-xl ${focused ? 'bg-[#2563eb] text-white scale-110 shadow-lg shadow-[#2563eb]/30' : 'text-white/30 hover:text-white/70'}`}
                  disabled={numPages ? pageNumber >= numPages : true}
                >
                  <span className="material-symbols-outlined text-[32px]">navigate_next</span>
                </button>
              )}
            </FocusableControl>
          </div>

          <div className="w-px h-10 bg-white/10 mx-2"></div>

          <FocusableControl 
            onFocus={() => {}} 
            onEnterPress={onClose}
            onClick={onClose}
            focusKey="MANUAL_CLOSE"
          >
            {(focused) => (
              <button className={`px-10 h-[64px] flex items-center gap-3 transition-all rounded-2xl font-black uppercase text-[12px] tracking-widest border-2 ${focused ? 'bg-white text-black scale-110 border-white ring-4 ring-white/20' : 'bg-white/5 text-white/60 border-white/5 hover:bg-white/10 hover:border-white/10 hover:text-white'}`}>
                <span className="material-symbols-outlined text-[24px]">close</span>
                Close Reader
              </button>
            )}
          </FocusableControl>
        </div>

        {/* Hint text */}
        <div className="text-[9px] geist-mono text-white/20 uppercase tracking-[0.3em] font-black mt-2">
          Paging: LB / RB • Zoom: D-Pad Up / Down • Close: B Button
        </div>
      </div>
    </FocusContext.Provider>
  );
};
