import type {CharacterData} from "@/types/CharacterJson.ts";
import {
  type AttributeWithValue,
  loadAttributesWithValues,
  loadProfession,
  loadRace,
  loadRaceVariant
} from "@/utils/loaders";
import {useCallback, useEffect, useState} from 'react';

export default function SheetHeader({jsonData}: { jsonData: CharacterData }) {
  const [raceName, setRaceName] = useState<string>(jsonData.r);
  const [raceVariantName, setRaceVariantName] = useState<string>(jsonData.rv || '');
  const [professionName, setProfessionName] = useState<string>(jsonData.p);
  const [attributes, setAttributes] = useState<AttributeWithValue[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  
  const resetToDefaults = useCallback(() => {
    setRaceName(jsonData.r);
    setRaceVariantName(jsonData.rv || '');
    setProfessionName(jsonData.p);
    setAttributes([]);
  }, [jsonData.r, jsonData.rv, jsonData.p]);
  
  const loadData = useCallback(async (signal: AbortSignal) => {
    setLoading(true);
    setError(null);
    
    try {
      // Load race and profession using the new loader functions
      const [race, raceVariant, profession, loadedAttributes] = await Promise.all([
        loadRace(jsonData.r),
        loadRaceVariant(jsonData.rv || ''),
        loadProfession(jsonData.p),
        loadAttributesWithValues(jsonData.attr.values),
      ]);
      
      // Check if component is still mounted and request wasn't cancelled
      if (signal.aborted) return;
      
      // Update state with loaded data
      setRaceName(race?.name || jsonData.r);
      setRaceVariantName(raceVariant?.name || '');
      
      // Handle profession name with gender preference
      if (profession?.name) {
        setProfessionName(profession.name.m || profession.name.f || jsonData.p);
      } else {
        setProfessionName(jsonData.p);
      }
      
      setAttributes(loadedAttributes);
    } catch (err) {
      if (signal.aborted) return;
      
      const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
      console.error('Error loading character data:', errorMessage);
      setError(errorMessage);
      
      // Reset to default values on error
      resetToDefaults();
    } finally {
      if (!signal.aborted) {
        setLoading(false);
      }
    }
  }, [jsonData.r, jsonData.rv, jsonData.p, jsonData.attr, resetToDefaults]);
  
  useEffect(() => {
    const abortController = new AbortController();
    
    loadData(abortController.signal);
    
    return () => {
      abortController.abort();
    };
  }, [loadData]);
  
  // Optional: Add loading state handling
  if (loading) {
    return <div className="animate-pulse">Loading character data...</div>;
  }
  
  // Optional: Add error state handling
  if (error) {
    return (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          Error loading character data: {error}
        </div>
    );
  }
  
  const calculateTotalLp = () => {
    // GW der Spezies + KO + KO
    const tempRaceLp = 5 // TODO: Needs to be pulled from universal stats
    const constVal = attributes.find(attr => attr.id === 'ATTR_7')?.value || 0; // ATTR_7 = Constitution
    const bonusMalus = 0 // Negative when malus
    const zukauf = 0
    return (jsonData.attr.lp + constVal * 2 + tempRaceLp + zukauf + bonusMalus);
  }
  
  const calculateTotalAP = () => {
    // TODO: Only show if Zauberer
    // 20 durch Zauberer + Leiteigenschaft
    const initial = 20
    const leiteigenschaft = 0 // TODO: needs to be pulled
    const bonusMalus = 0 // Negative when malus
    const zukauf = 0
    return (jsonData.attr.ae + initial + leiteigenschaft + bonusMalus + zukauf);
  }
  
  const calculateTotalKP = () => {
    // TODO: Only show if Geweihter
    // 20 durch Geweiht + Leiteigenschaft
    const initial = 20
    const leiteigenschaft = 0 // TODO: needs to be pulled
    const bonusMalus = 0 // Negative when malus
    const zukauf = 0
    return (jsonData.attr.kp + initial + leiteigenschaft + bonusMalus + zukauf);
  }
  
  const calculateTotalSp = () => {
    // TODO: needs to be pulled
    const initial = 3
    const bonus = 0
    return (jsonData.attr.sp || 0 + initial + bonus);
  }
  
  
  return (
      <>
        <div className="flex justify-between items-end py-5 px-5">
          <div className="w-[30%]">
            <p className="border-b border-gray-500 font-semibold">
              {jsonData.name}
            </p>
            <small className="text-gray-400">Name</small>
          </div>
          <div className="w-[30%]">
            <p className="border-b border-gray-500 font-semibold">
              {raceName} {raceVariantName ? <>({raceVariantName})</> : ''}
            </p>
            <small className="text-gray-400">Spezies</small>
          </div>
          <div className="w-[30%]">
            <p className="border-b border-gray-500 font-semibold">
              {professionName}
            </p>
            <small className="text-gray-400">Profession</small>
          </div>
        </div>
        
        <div className="flex justify-between items-center py-5 px-5 gap-6">
          <div className="w-[30%] h-full rounded-md bg-gray-600 overflow-hidden"
               style={{height: '12.5em', width: '9.375em'}}>
            <img src="#" alt="char bild" className="object-cover w-full h-full"/>
          </div>
          
          <div className="w-[70%] flex flex-col gap-2 w-[80%]">
            <div className="w-[100%] flex justify-between">
              {attributes.map(attr => (
                  <div key={attr.id} className="">
                    <div className="relative group cursor-help flex items-center justify-center">
                      <div>{attr.short}</div>
                      <span
                          className="absolute left-1/2 transform -translate-x-1/2 bottom-full bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap">
                        {attr.name}
                      </span>
                    </div>
                    <span className="font-bold" style={{fontSize: '1.5em'}}>{attr.value}</span>
                  </div>
              ))}
            </div>
            
            <div className="w-[100%] flex pt-2">
                  <span className="relative group cursor-help">
                    LP
                    <span
                        className="absolute left-0 bottom-full mb-1 px-2 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap">
                      Lebenspunkte
                    </span>
                  </span>
              <div
                  className="ms-5 w-[100%] bg-gray-600 rounded-full h-6 flex items-center overflow-hidden relative">
                <div
                    className="bg-gradient-to-r from-red-900 to-red-600 h-full transition-all duration-300"
                    style={{width: `${Math.min(((calculateTotalLp() - jsonData.attr.permanentLP.lost) / calculateTotalLp()) * 100, 100)}%`}}
                />
                <div className="absolute inset-0 flex items-center justify-center text-white text-sm font-medium">
                  {calculateTotalLp()} / {calculateTotalLp() - jsonData.attr.permanentLP.lost}
                </div>
              </div>
            </div>
            
            <div className="w-[100%] flex pt-2">
                  <span className="relative group cursor-help">
                    AP
                    <span
                        className="absolute left-0 bottom-full mb-1 px-2 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap">
                      Astralpunkte
                    </span>
                  </span>
              <div
                  className="ms-5 w-[100%] bg-gray-600 rounded-full h-6 flex items-center overflow-hidden relative">
                <div
                    className="bg-gradient-to-r from-blue-900 to-blue-500 h-full transition-all duration-300"
                    style={{width: `${Math.min(((calculateTotalAP() - jsonData.attr.permanentAE.lost) / calculateTotalAP()) * 100, 100)}%`}}
                />
                <div className="absolute inset-0 flex items-center justify-center text-white text-sm font-medium">
                  {calculateTotalAP()} / {calculateTotalAP() - jsonData.attr.permanentAE.lost}
                </div>
              </div>
            </div>
            
            <div className="w-[100%] flex pt-2">
                  <span className="relative group cursor-help">
                    KP
                    <span
                        className="absolute left-0 bottom-full mb-1 px-2 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap">
                      Karmapunkte
                    </span>
                  </span>
              <div
                  className="ms-5 w-[100%] bg-gray-600 rounded-full h-6 flex items-center overflow-hidden relative">
                <div
                    className="bg-gradient-to-r from-emerald-900 to-emerald-500 h-full transition-all duration-300"
                    style={{width: `${Math.min(((calculateTotalKP() - jsonData.attr.permanentKP.lost) / calculateTotalKP()) * 100, 100)}%`}}
                />
                <div className="absolute inset-0 flex items-center justify-center text-white text-sm font-medium">
                  {calculateTotalKP()} / {calculateTotalKP() - jsonData.attr.permanentKP.lost}
                </div>
              </div>
            </div>
            
            <div className="w-[100%] flex pt-2">
                  <span className="relative group cursor-help">
                    SP
                    <span
                        className="absolute left-0 bottom-full mb-1 px-2 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap">
                      Schicksalspunkte
                    </span>
                  </span>
              <div className="ms-5 w-[100%] flex items-center gap-2">
                {Array.from({length: calculateTotalSp()}, (_, index) => (
                    <div
                        key={`sp-available-${index}`}
                        className="rounded-full w-5 h-5 bg-gradient-to-br from-violet-700 to-violet-500"
                    />
                ))}
              </div>
            </div>
          </div>
        </div>
      </>
  )
}
