"use client";

import { useState } from "react";
import { ArrowLeft } from "lucide-react";
import { useSkills } from "@/hooks/useSkills";
import { SkillList } from "./SkillList";
import { SkillDetail } from "./SkillDetail";

export function SkillsView() {
  const {
    skills,
    loading,
    selectedSkill,
    selectSkill,
    addSkillFromPath,
    addSkillFromFile,
    updateSkill,
    deleteSkill,
    updateAgents,
  } = useSkills();
  const [mobileShowDetail, setMobileShowDetail] = useState(false);

  const handleToggleAgent = (agentName: string, enabled: boolean) => {
    if (!selectedSkill) return;
    const newAgents = enabled
      ? [...selectedSkill.agents, agentName]
      : selectedSkill.agents.filter((a) => a !== agentName);
    updateAgents(selectedSkill.name, newAgents);
  };

  const handleSelect = (name: string) => {
    selectSkill(name);
    setMobileShowDetail(true);
  };

  return (
    <div className="flex h-full flex-col md:flex-row">
      <div className={`shrink-0 ${mobileShowDetail ? "hidden md:block" : ""} md:w-72`}>
        <SkillList
          skills={skills}
          loading={loading}
          selectedName={selectedSkill?.name}
          onSelect={handleSelect}
          onAddFromPath={addSkillFromPath}
          onAddFromFile={addSkillFromFile}
          onDelete={deleteSkill}
        />
      </div>
      <div className={`flex-1 ${!mobileShowDetail ? "hidden md:flex" : ""}`}>
        {selectedSkill ? (
          <div className="flex h-full flex-col">
            <button
              onClick={() => setMobileShowDetail(false)}
              className="flex items-center gap-1.5 px-3 py-2.5 text-sm text-zinc-500 hover:text-zinc-700 md:hidden dark:text-zinc-400 dark:hover:text-zinc-200"
            >
              <ArrowLeft size={16} />
              Back to skills
            </button>
            <div className="flex-1 overflow-auto">
              <SkillDetail
                skill={selectedSkill}
                onUpdate={updateSkill}
                onToggleAgent={handleToggleAgent}
              />
            </div>
          </div>
        ) : (
          <div className="flex h-full items-center justify-center">
            <p className="text-sm text-zinc-400">Select a skill to view details</p>
          </div>
        )}
      </div>
    </div>
  );
}
