import { useState, useEffect, useRef } from "react";
import { getGameTalents } from "../api";
import type { GameTalent } from "../types";
import styles from "./TalentPicker.module.css";

interface TalentPickerProps {
  onSelect: (talent: GameTalent) => void;
  onCustom: () => void;
  onClose: () => void;
}

export default function TalentPicker({
  onSelect,
  onCustom,
  onClose,
}: TalentPickerProps) {
  const [talents, setTalents] = useState<GameTalent[]>([]);
  const [search, setSearch] = useState("");
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    getGameTalents().then(setTalents);
  }, []);

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(e.target as Node)
      ) {
        onClose();
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [onClose]);

  const filtered = search
    ? talents.filter(
        (t) =>
          t.name.toLowerCase().includes(search.toLowerCase()) ||
          t.source.toLowerCase().includes(search.toLowerCase()),
      )
    : talents;

  const groups: Record<string, GameTalent[]> = {};
  for (const talent of filtered) {
    if (!groups[talent.source]) groups[talent.source] = [];
    groups[talent.source].push(talent);
  }

  return (
    <div className={styles.container} ref={containerRef}>
      <input
        className={styles.searchInput}
        type="text"
        placeholder="Search talents..."
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        autoFocus
      />
      <div className={styles.dropdown}>
        {Object.entries(groups).map(([source, groupTalents]) => (
          <div key={source} className={styles.group}>
            <div className={styles.groupLabel}>{source}</div>
            {groupTalents.map((talent) => (
              <div
                key={talent.id}
                className={styles.item}
                onClick={() => onSelect(talent)}
              >
                <span className={styles.itemName}>{talent.name}</span>
                <span className={styles.itemDesc}>{talent.description}</span>
              </div>
            ))}
          </div>
        ))}
        <div className={styles.customOption} onClick={onCustom}>
          Custom talent...
        </div>
      </div>
    </div>
  );
}
