import { useState, useEffect } from "react";
import type { Character, GameItem, CharacterSpell, SpellCastResult } from "../types";
import { getCharacterSpells, restCharacter } from "../api";
import CharacterSheet from "./CharacterSheet";
import SpellList from "./SpellList";
import SpellCastResultModal from "./SpellCastResult";
import styles from "./CharacterDetail.module.css";

interface CharacterDetailProps {
  character: Character;
  campaignId: number;
  critKeys?: Set<string>;
  onUpdate: (id: number, data: Partial<Character>) => void;
  onStatChange: (characterId: number, statName: string, value: number) => void;
  onAddGearFromItem: (characterId: number, item: GameItem) => void;
  onAddGearCustom: (
    characterId: number,
    data: { name: string; type: string; slot_count: number },
  ) => void;
  onRemoveGear: (characterId: number, gearId: number) => void;
  onAddTalent: (
    characterId: number,
    data: {
      name: string;
      description: string;
      effect?: Record<string, unknown>;
      game_talent_id?: number | null;
    },
  ) => void;
  onRemoveTalent: (characterId: number, talentId: number) => void;
  onDelete: (id: number) => void;
  onClose: () => void;
  canEdit?: boolean;
}

export default function CharacterDetail({
  character,
  campaignId,
  critKeys,
  onUpdate,
  onStatChange,
  onAddGearFromItem,
  onAddGearCustom,
  onRemoveGear,
  onAddTalent,
  onRemoveTalent,
  onDelete,
  onClose,
  canEdit = true,
}: CharacterDetailProps) {
  const [mode, setMode] = useState<"view" | "edit">("view");
  const [spells, setSpells] = useState<CharacterSpell[]>([]);
  const [castResult, setCastResult] = useState<{ result: SpellCastResult; spellName: string } | null>(null);

  useEffect(() => {
    if (["Wizard", "Priest"].includes(character.class)) {
      getCharacterSpells(character.id).then(setSpells);
    }
  }, [character.id, character.class]);

  async function handleRest() {
    await restCharacter(character.id);
    setSpells((prev) => prev.map((s) => ({ ...s, exhausted: 0, focus_active: 0, focus_started_at: null })));
  }

  return (
    <div className={styles.overlay} onClick={onClose}>
      <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
        <div className={styles.topBar}>
          {canEdit && (
            <button
              className={`${styles.editBtn} ${mode === "edit" ? styles.active : ""}`}
              onClick={() => setMode(mode === "view" ? "edit" : "view")}
            >
              {mode === "view" ? "Edit" : "Done"}
            </button>
          )}
          <button className={styles.closeBtn} onClick={onClose}>
            ✕
          </button>
        </div>

        <SpellList
          characterId={character.id}
          characterClass={character.class}
          spells={spells}
          mode={mode}
          canEdit={canEdit}
          onSpellAdded={(spell) => setSpells((prev) => [...prev, spell])}
          onSpellRemoved={(spellId) =>
            setSpells((prev) => prev.filter((s) => s.spell_id !== spellId))
          }
          onSpellCast={(result, spellName) => setCastResult({ result, spellName })}
          onSpellsUpdated={setSpells}
        />

        {canEdit && ["Wizard", "Priest"].includes(character.class) && (
          <div className={styles.restRow}>
            <button className={styles.restBtn} onClick={handleRest}>
              Take Rest
            </button>
          </div>
        )}

        <CharacterSheet
          character={character}
          mode={mode}
          campaignId={campaignId}
          critKeys={critKeys}
          onUpdate={onUpdate}
          onStatChange={onStatChange}
          onAddGearFromItem={onAddGearFromItem}
          onAddGearCustom={onAddGearCustom}
          onRemoveGear={onRemoveGear}
          onAddTalent={onAddTalent}
          onRemoveTalent={onRemoveTalent}
          onDelete={onDelete}
        />
      </div>

      {castResult && (
        <SpellCastResultModal
          result={castResult.result}
          spellName={castResult.spellName}
          onClose={() => setCastResult(null)}
        />
      )}
    </div>
  );
}
