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

interface CollectionModalProps {
  onClose: () => void;
  onSelect: (collection: RommCollection) => void;
  onCreate: (name: string) => void;
  collections: RommCollection[];
}

const CollectionItem = ({ collection, onSelect }: { collection: RommCollection, onSelect: () => void }) => {
  const { ref, focused } = useFocusable({
    onEnterPress: onSelect,
  });

  return (
    <div
      ref={ref}
      onClick={onSelect}
      className={`p-2.5 px-4 mb-1.5 rounded-[12px] border transition-all duration-300 cursor-pointer flex items-center gap-3 ${
        focused
          ? 'border-[#2563eb] bg-[#2563eb]/20 scale-[1.01] text-white shadow-[0_0_15px_rgba(37,99,235,0.15)] font-bold'
          : 'border-white/5 bg-white/5 text-white/50 hover:border-white/10'
      }`}
    >
      <div className={`w-8 h-8 rounded-[8px] flex items-center justify-center transition-colors ${focused ? 'bg-[#2563eb] text-white' : 'bg-white/5 text-white/30'}`}>
        <span className="material-symbols-outlined text-[16px]">folder</span>
      </div>
      <span className="text-[14px] tracking-tight">{collection.name}</span>
      {focused && (
        <span className="ml-auto material-symbols-outlined text-[16px] animate-pulse opacity-50">
          chevron_right
        </span>
      )}
    </div>
  );
};

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

  return (
    <button
      ref={ref}
      onClick={onClick}
      className={`${className} ${focused ? 'ring-2 ring-white/50 bg-[#2563eb]/80' : 'hover:bg-white/10'}`}
      title={title}
    >
      {children}
    </button>
  );
};

export const CollectionModal = ({ onClose, onSelect, onCreate, collections }: CollectionModalProps) => {
  const { ref, focusKey } = useFocusable({
    isFocusBoundary: true,
    focusKey: 'COLLECTION_MODAL'
  });

  const { mode } = useInputMode();
  const [newCollectionName, setNewCollectionName] = useState('');
  const [isCreating, setIsCreating] = useState(false);

  useEffect(() => {
    // Force focus into modal after a short delay for registration
    const timer = setTimeout(() => {
      setFocus('COLLECTION_MODAL');
    }, 50);
    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    if (isCreating && mode === 'gamepad') {
      // Small delay to ensure VirtualKeyboard is mounted and registered its focus key
      const timer = setTimeout(() => {
        setFocus('VIRTUAL_KEYBOARD_ZONE');
      }, 150);
      return () => clearTimeout(timer);
    }
  }, [isCreating, mode]);

  const handleKeyPress = (key: string) => {
    if (key === 'BACKSPACE') {
      setNewCollectionName((prev: string) => prev.slice(0, -1));
    } else if (key === 'SPACE') {
      setNewCollectionName((prev: string) => prev + ' ');
    } else if (key === 'ENTER') {
      if (newCollectionName.trim()) {
        onCreate(newCollectionName.trim());
        setNewCollectionName('');
        setIsCreating(false);
      }
    } else {
      setNewCollectionName((prev: string) => prev + key);
    }
  };

  return (
    <FocusContext.Provider value={focusKey}>
      <div 
        className="fixed inset-0 z-[100] flex items-center justify-center p-6 bg-black/60 backdrop-blur-xl animate-in fade-in duration-500"
        onClick={onClose}
      >
        <div 
          ref={ref}
          className="w-full max-w-[660px] bg-[#121416]/95 border border-white/10 rounded-[32px] overflow-hidden shadow-[0_32px_128px_-16px_rgba(0,0,0,0.8)] flex flex-col max-h-[70vh] animate-in zoom-in-95 slide-in-from-bottom-10 duration-500 ring-1 ring-white/5"
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header - Minimalist Atelier */}
          <div className="p-6 pb-4 border-b border-white/5 bg-gradient-to-r from-[#2563eb]/5 to-transparent flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-1 h-4 bg-[#2563eb] rounded-full" />
              <h2 className="text-[18px] font-black text-white/90 tracking-tighter uppercase geist-mono">Add to Collection</h2>
            </div>
            
            <div className="flex items-center gap-2">
              <HeaderButton 
                onClick={() => setIsCreating(true)}
                className="flex items-center gap-2 px-4 h-9 rounded-[10px] bg-[#2563eb] text-white text-[11px] font-black uppercase tracking-widest transition-all shadow-lg shadow-[#2563eb]/20"
              >
                <span className="material-symbols-outlined text-[16px]">add</span>
                New
              </HeaderButton>
              
              <HeaderButton 
                onClick={onClose} 
                className="w-9 h-9 flex items-center justify-center rounded-[10px] bg-white/5 text-white/40 hover:text-white transition-all"
                title="Close"
              >
                <span className="material-symbols-outlined text-[18px]">close</span>
              </HeaderButton>
            </div>
          </div>

          {/* List Content */}
          <div className="flex-1 overflow-y-auto p-6 scrollbar-hide">
            {/* Create New Flow (Inline at top) */}
            {isCreating && (
              <div className="p-1 mb-4 rounded-[18px] bg-gradient-to-br from-[#2563eb] to-[#1d4ed8] shadow-[0_0_40px_rgba(37,99,235,0.2)] animate-in slide-in-from-top-4 duration-300">
                <div className="bg-[#0c0d0e] rounded-[17px] p-4 flex items-center gap-3">
                  <span className="material-symbols-outlined text-[#2563eb] text-[20px]">edit_note</span>
                  <input
                    autoFocus
                    type="text"
                    placeholder="New collection name..."
                    className="flex-1 bg-transparent border-none outline-none text-white placeholder-white/10 text-[15px] font-medium"
                    value={newCollectionName}
                    onChange={(e) => setNewCollectionName(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && newCollectionName.trim()) {
                        onCreate(newCollectionName.trim());
                        setNewCollectionName('');
                        setIsCreating(false);
                      }
                      if (e.key === 'Escape') setIsCreating(false);
                    }}
                  />
                  <div className="flex items-center gap-2">
                     <button 
                      onClick={() => setIsCreating(false)}
                      className="p-1.5 text-white/20 hover:text-white transition-colors"
                     >
                       <span className="material-symbols-outlined text-[18px]">close</span>
                     </button>
                     <button 
                      disabled={!newCollectionName.trim()}
                      onClick={() => {
                        onCreate(newCollectionName.trim());
                        setNewCollectionName('');
                        setIsCreating(false);
                      }}
                       className="p-1.5 bg-[#2563eb] text-white rounded-[6px] hover:bg-[#1d4ed8] disabled:opacity-50 transition-all"
                     >
                       <span className="material-symbols-outlined text-[18px]">check</span>
                     </button>
                  </div>
                </div>
              </div>
            )}

            {isCreating && mode === 'gamepad' && (
              <VirtualKeyboard 
                onKeyPress={handleKeyPress} 
                onClose={() => setIsCreating(false)}
              />
            )}

            <div className="space-y-1">
              {collections.map((col) => (
                <CollectionItem 
                  key={col.id} 
                  collection={col} 
                  onSelect={() => onSelect(col)} 
                />
              ))}
              
              {collections.length === 0 && !isCreating && (
                <div className="py-12 text-center rounded-[24px] border border-dashed border-white/5 bg-white/[0.01]">
                   <span className="material-symbols-outlined text-white/5 mb-2 block text-[32px]">inventory_2</span>
                   <p className="text-[10px] font-bold text-white/10 uppercase tracking-[0.5em]">Archive Empty</p>
                </div>
              )}
            </div>
          </div>

          {/* Bottom Atelier Trim - Removed as requested */}
        </div>
      </div>
    </FocusContext.Provider>
  );
};
