import { useEffect } from 'react';
import { useFocusable, FocusContext, setFocus } from '@noriginmedia/norigin-spatial-navigation';
import { useInputMode } from '../context/InputModeContext';

interface VirtualKeyboardProps {
  onKeyPress: (key: string) => void;
  onClose?: () => void;
}

const Key = ({ label, onKeyPress, width = 'w-12' }: { label: string, onKeyPress: (key: string) => void, width?: string }) => {
  const { ref, focused } = useFocusable({
    onEnterPress: () => onKeyPress(label),
  });

  const displayLabel = label === 'BACKSPACE' ? '⌫' : label === 'SPACE' ? 'SPACE' : label === 'ENTER' ? 'ENTER' : label;
  const isAction = ['BACKSPACE', 'SPACE', 'ENTER'].includes(label);

  return (
    <div
      ref={ref}
      onClick={() => onKeyPress(label)}
      className={`${width} h-12 flex items-center justify-center rounded-[10px] border transition-all duration-200 cursor-pointer ${
        focused
          ? 'bg-[#2563eb] border-[#2563eb] text-white scale-110 shadow-[0_0_20px_rgba(37,99,235,0.4)] z-10'
          : 'bg-white/5 border-white/5 text-white/40 hover:bg-white/10 hover:border-white/10'
      } ${isAction ? 'px-4 flex-1' : ''}`}
    >
      <span className={`font-bold ${isAction ? 'text-[10px] tracking-widest' : 'text-sm'}`}>{displayLabel}</span>
    </div>
  );
};

const KeyboardActionButton = ({ onClick, children, className }: { onClick: () => void, children: React.ReactNode, className: string }) => {
  const { ref, focused } = useFocusable({
    onEnterPress: onClick,
  });

  return (
    <button
      ref={ref}
      onClick={onClick}
      className={`${className} ${focused ? 'bg-white/20 text-white ring-2 ring-white/20 scale-105' : ''}`}
    >
      {children}
    </button>
  );
};

export const VirtualKeyboard = ({ onKeyPress, onClose }: VirtualKeyboardProps) => {
  const { mode } = useInputMode();
  const { ref, focusKey } = useFocusable({
    isFocusBoundary: true,
    focusKey: 'VIRTUAL_KEYBOARD_ZONE'
  });

  useEffect(() => {
    if (mode === 'gamepad') {
      const timer = setTimeout(() => {
        setFocus('VIRTUAL_KEYBOARD_ZONE');
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [mode]);

  const rows = [
    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],
    ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'],
    ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', '.'],
    ['Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '!', '?'],
    ['BACKSPACE', 'SPACE', 'ENTER']
  ];

  return (
    <FocusContext.Provider value={focusKey}>
      <div 
        ref={ref}
        className="mt-6 p-6 bg-white/[0.02] border border-white/5 rounded-[24px] backdrop-blur-sm animate-in fade-in zoom-in-95 duration-500"
      >
        <div className="space-y-1.5 max-w-[540px] mx-auto">
          {rows.map((row, i) => (
            <div key={i} className="flex gap-1.5 justify-center">
              {row.map(key => {
                let width = 'w-11';
                if (key === 'BACKSPACE') width = 'w-[124px]';
                if (key === 'SPACE') width = 'w-[180px]';
                if (key === 'ENTER') width = 'w-[124px]';
                
                return (
                  <Key 
                    key={key} 
                    label={key} 
                    onKeyPress={onKeyPress} 
                    width={width}
                  />
                );
              })}
            </div>
          ))}
        </div>
        
        {onClose && (
          <div className="mt-4 flex justify-center">
             <KeyboardActionButton 
              onClick={onClose}
              className="px-6 py-2 rounded-full bg-white/5 text-white/20 text-[10px] font-bold uppercase tracking-[0.2em] transition-all"
             >Hide Keyboard</KeyboardActionButton>
          </div>
        )}
      </div>
    </FocusContext.Provider>
  );
};
