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

export default function Skills({ jsonData }: { jsonData: CharacterData }) {
  const [skills, setSkills] = useState<SkillWithValue[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    const loadData = async () => {
      try {
        setLoading(true);
        // Load skills with their values using the new loader function
        const loadedSkills = await loadSkillsWithValues(jsonData.talents);

        if (isMounted) {
          setSkills(loadedSkills);
          setLoading(false);
        }
      } catch (error) {
        console.error('Error loading skills:', error);
        if (isMounted) {
          setError('Failed to load skills. Please try again.');
          setLoading(false);
        }
      }
    };

    loadData();

    return () => {
      isMounted = false;
    };
  }, [jsonData.talents]);

  if (loading) {
    return <div>Loading skills...</div>;
  }

  if (error) {
    return <div className="text-red-500">{error}</div>;
  }

  if (skills.length === 0) {
    return <div>No skills found.</div>;
  }

  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">
                {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>
  );
}
