import {useCallback, useEffect, useState} from 'react';
import type {CharacterData} from '@/types/CharacterJson.ts';
import {loadSkillsWithValues, type SkillWithValue} from '@/utils/loaders.ts';

export default function Skills({jsonData}: { jsonData: CharacterData }) {
  const [skills, setSkills] = useState<SkillWithValue[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  
  const resetToDefaults = useCallback(() => {
    setSkills([]);
  }, []);
  
  const loadData = useCallback(async (signal: AbortSignal) => {
    setLoading(true);
    setError(null);
    
    try {
      // Load skills with their values using the new loader function
      const loadedSkills = await loadSkillsWithValues(jsonData.talents);
      
      // Check if component is still mounted and request wasn't cancelled
      if (signal.aborted) return;
      
      setSkills(loadedSkills);
    } catch (err) {
      if (signal.aborted) return;
      
      const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
      console.error('Error loading skills:', errorMessage);
      setError('Failed to load skills. Please try again.');
      
      // Reset to default values on error
      resetToDefaults();
    } finally {
      if (!signal.aborted) {
        setLoading(false);
      }
    }
  }, [jsonData.talents, resetToDefaults]);
  
  useEffect(() => {
    const abortController = new AbortController();
    
    loadData(abortController.signal);
    
    return () => {
      abortController.abort();
    };
  }, [loadData]);
  
  if (loading) {
    return <div className="animate-pulse">Loading skills...</div>;
  }
  
  if (error) {
    return (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          Error loading skills: {error}
        </div>
    );
  }
  
  if (skills.length === 0) {
    return <div>No skills found.</div>;
  }
  
  console.log(jsonData);
  
  return (
      <div className="p-4">
        <h1 className="text-2xl font-bold mb-4">Skills</h1>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {skills.map(skill => (
              <div key={skill.id} className="border p-3 rounded shadow">
                <div className="flex justify-between items-center">
                  <h2 className="text-lg font-semibold">{skill.name}</h2>
                  <span
                      className="bg-blue-100 text-blue-800 font-bold px-2 py-1 rounded flex items-center justify-center"
                      style={{width: '2.5em'}}>
                {skill.value}
              </span>
                </div>
                {/*{skill.applications && skill.applications.length > 0 && (*/}
                {/*  <div className="mt-2">*/}
                {/*    <h3 className="font-medium">Applications:</h3>*/}
                {/*    <ul className="list-disc list-inside">*/}
                {/*      {skill.applications.map((app: any, index: number) => (*/}
                {/*        <li key={index}>{app.name}</li>*/}
                {/*      ))}*/}
                {/*    </ul>*/}
                {/*  </div>*/}
                {/*)}*/}
                {skill.tools && (
                    <div className="mt-2">
                      <h3 className="font-medium">Tools:</h3>
                      <p className="text-sm">{skill.tools}</p>
                    </div>
                )}
              </div>
          ))}
        </div>
      </div>
  );
}
