import { useState, useCallback, useMemo } from 'react';
import { Header } from '@/components/Header';
import { FilterDropdown } from '@/components/FilterDropdown';
import { SkillList } from '@/components/SkillList';
import { SkillViewer, extractToc, TocItem } from '@/components/SkillViewer';
import { TableOfContents } from '@/components/TableOfContents';
import { useSearch } from '@/hooks/useSearch';
import { SkillsData, Skill } from '@/types/skills';
import skillsData from '@/data/skills.json';
import { getCategoryCounts } from '@/lib/skills-utils';
import { fetchSkillContent } from '@/lib/skills-api';

export function App() {
  const data = skillsData as SkillsData;
  const categoryCounts = useMemo(() => getCategoryCounts(data.skills), [data.skills]);
  const [selectedSkill, setSelectedSkill] = useState<Skill | null>(null);
  const [skillContent, setSkillContent] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState('all');

  const { skills, total } = useSearch({
    query,
    category,
    skills: data.skills,
  });

  const toc: TocItem[] = skillContent ? extractToc(skillContent) : [];

  const loadSkillContent = useCallback(async (skill: Skill) => {
    setIsLoading(true);
    setSkillContent(null);
    try {
      const content = await fetchSkillContent(skill);
      setSkillContent(content);
    } catch (error) {
      console.error('Error loading skill:', error);
      const message = error instanceof Error ? error.message : 'Unknown error';
      setSkillContent(
        `## Failed to load skill\n\n${message}\n\nEnsure the WebUI server is running (\`miokit webui\`) or use \`npm run dev\` from \`miokit-webui/\` for development.`
      );
    } finally {
      setIsLoading(false);
    }
  }, []);

  const handleSelectSkill = useCallback(
    (skill: Skill) => {
      setSelectedSkill(skill);
      loadSkillContent(skill);
    },
    [loadSkillContent]
  );

  return (
    <div className="flex h-screen flex-col overflow-hidden bg-background">
      <Header
        totalSkills={data.totalCount}
        filteredCount={total}
        query={query}
        onQueryChange={setQuery}
      />

      <div className="mx-auto flex w-full max-w-[1680px] flex-1 min-h-0 flex-col gap-4 overflow-hidden px-4 py-4 sm:gap-6 sm:px-6 lg:px-8 xl:flex-row">
        <aside className="relative z-20 flex max-h-[38vh] shrink-0 flex-col gap-3 min-h-0 overflow-visible xl:max-h-none xl:w-[320px] 2xl:w-[360px]">
          <div className="relative z-20 shrink-0 overflow-visible">
            <FilterDropdown
              categories={data.categories}
              categoryCounts={categoryCounts}
              selectedCategory={category}
              filteredCount={total}
              onSelect={setCategory}
            />
          </div>

          <div className="glass-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl">
            <SkillList
              skills={skills}
              selectedSkill={selectedSkill}
              onSelect={handleSelectSkill}
            />
          </div>
        </aside>

        <main className="flex min-h-0 min-w-0 flex-1 flex-col">
          <div className="glass-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl">
            <SkillViewer
              skill={selectedSkill}
              content={skillContent}
              isLoading={isLoading}
            />
          </div>
        </main>

        <aside className="hidden min-h-0 w-56 shrink-0 2xl:flex 2xl:flex-col">
          <div className="glass-panel min-h-0 flex-1 overflow-hidden rounded-xl">
            <TableOfContents toc={toc} />
          </div>
        </aside>
      </div>
    </div>
  );
}
