import React, { useState } from 'react';
import { Plus } from 'lucide-react';
import { Character, Locale } from '../types/Character';
import CharacterCard from './CharacterCard';
import CharacterInfo from './CharacterInfo';
import { fetchNui } from '../utils/fetchNui';

interface CharacterSelectionProps {
  initialCharacters: Character[];
  Candelete: boolean;
  MaxAllowedSlot : number;
  locale : Locale;
  logo : string;
}

const CharacterSelection: React.FC<CharacterSelectionProps> = ({ initialCharacters, Candelete, MaxAllowedSlot, locale, logo }) => {
  const [characters, setCharacters] = useState<Character[]>(initialCharacters);
  const [showInfo, setShowInfo] = useState<string | null>(null);
  const [selectedCharacter, setSelectedCharacter] = useState<Character | null>(
    characters.find(char => char.isActive) || null
  );

  const handleSelectCharacter = (id: string) => {
    if (selectedCharacter?.id === id) return;

    const updatedCharacters = characters.map(char => ({
      ...char,
      isActive: char.id === id
    }));
    
    setCharacters(updatedCharacters);
    setSelectedCharacter(updatedCharacters.find(char => char.id === id) || null);
    setShowInfo(null);
    fetchNui('SelectCharacter', {id : id})
  };

  const toggleInfo = (id: string) => {
    setShowInfo(showInfo === id ? null : id);
  };

  const PlayCharacter = () => {
    fetchNui('PlayCharacter')
  }

  const handleCreateCharacter = () => {
    fetchNui('CreateCharacter')
  }

  const handleDeleteCharacter = () => {
    if (!selectedCharacter) return;

    const updatedCharactersRaw = characters.filter(char => char.id !== selectedCharacter.id);

    fetchNui('DeleteCharacter');

    if (updatedCharactersRaw.length > 0) {
      const updatedCharacters = updatedCharactersRaw.map((char, index) => ({
        ...char,
        isActive: index === 0
      }));

      setCharacters(updatedCharacters);
      setSelectedCharacter(updatedCharacters[0]);
      setShowInfo(null);
    } else {
      setCharacters([]);
      setSelectedCharacter(null);
      setShowInfo(null);
      handleCreateCharacter();
    }
  };

  return (
    <div className="h-screen bg-black/60 backdrop-blur-md text-white w-[450px] border-r border-[#ef444433] overflow-hidden animate-slideIn flex flex-col shadow-2xl">
      <div className="p-6 flex-1 overflow-auto custom-scrollbar">
        <div className="flex items-center justify-between mb-8">
          <img src={logo} alt="Logo" className="h-[70px] w-auto object-contain drop-shadow-[0_0_10px_rgba(239,68,68,0.5)]" />
          <div className="text-right">
            <h2 className="text-[28px] font-black tracking-tighter uppercase italic text-transparent bg-clip-text bg-gradient-to-r from-red-500 to-red-800">{locale.title}</h2>
            <div className="h-1 w-full bg-gradient-to-r from-transparent via-red-600 to-transparent mt-1"></div>
          </div>
        </div>
        
        <div className="space-y-2">
          {characters.map(character => (
            <div key={character.id}>
              <CharacterCard 
                character={character} 
                onSelect={handleSelectCharacter}
                onInfoClick={toggleInfo}
                showInfo={showInfo === character.id}
                PlayCharacter={PlayCharacter}
              />
              {character.isActive && showInfo === character.id && (
                <CharacterInfo 
                  character={character} 
                  onClose={() => setShowInfo(null)}
                  isAllowedtoDelete={Candelete}
                  PlayCharacter={PlayCharacter}
                  handleDelete={handleDeleteCharacter}
                  locale={locale}
                />
              )}
            </div>
          ))}
        </div>
      </div>
      
      <div className="p-6 border-t border-[#ef444433] bg-black/40">
        <button 
          className={`w-full h-[60px] ${characters.length >= MaxAllowedSlot ? 'bg-neutral-800 cursor-not-allowed text-neutral-600' : 'bg-gradient-to-r from-red-600 to-red-800 cursor-pointer hover:from-red-500 hover:to-red-700 hover:shadow-[0_0_20px_rgba(239,68,68,0.4)]'} text-white font-bold uppercase tracking-widest rounded-lg flex items-center justify-center transition-all duration-300 transform active:scale-95`}
          onClick={handleCreateCharacter}
          disabled={characters.length >= MaxAllowedSlot}  
        >
          <Plus size={24} className="mr-2" />
          <span>Créer un personnage</span>
        </button>
      </div>
    </div>
  );
};

export default CharacterSelection;