import { useState } from "react";
import type { Character, GameItem } from "../types";
import CharacterSheet from "./CharacterSheet";
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;
}

export default function CharacterDetail({
  character,
  campaignId,
  critKeys,
  onUpdate,
  onStatChange,
  onAddGearFromItem,
  onAddGearCustom,
  onRemoveGear,
  onAddTalent,
  onRemoveTalent,
  onDelete,
  onClose,
}: CharacterDetailProps) {
  const [mode, setMode] = useState<"view" | "edit">("view");

  return (
    <div className={styles.overlay} onClick={onClose}>
      <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
        <div className={styles.topBar}>
          <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>

        <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>
    </div>
  );
}
