import { useState } from "react";
import type { CreateCharacterData } from "../api.js";
import SelectDropdown from "./SelectDropdown.js";
import { BACKGROUNDS, type Background } from "../data/backgrounds.js";
import {
  rollAllStats,
  rollStartingHp,
  rollStartingGold,
  startingGearSlots,
  getStartingTitle,
} from "../utils/character-creation.js";
import { getModifier, formatModifier } from "../utils/modifiers.js";
import styles from "./CharacterWizard.module.css";

const CLASSES = ["Fighter", "Priest", "Thief", "Wizard"];
const ANCESTRIES = ["Human", "Elf", "Dwarf", "Halfling", "Goblin", "Half-Orc"];
const ALIGNMENTS = ["Lawful", "Neutral", "Chaotic"];
const STAT_NAMES = ["STR", "DEX", "CON", "INT", "WIS", "CHA"];

const STEP_LABELS = [
  "Step 1 of 4 — Name & Origins",
  "Step 2 of 4 — Ability Scores",
  "Step 3 of 4 — Background & Beliefs",
  "Step 4 of 4 — Review & Create",
];

interface Props {
  campaignId: number;
  onSubmit: (data: CreateCharacterData) => Promise<void>;
  onClose: () => void;
}

export default function CharacterWizard({ onSubmit, onClose }: Props) {
  const [step, setStep] = useState(0);

  // Step 1
  const [name, setName] = useState("");
  const [charClass, setCharClass] = useState("Fighter");
  const [ancestry, setAncestry] = useState("Human");

  // Step 2
  const [stats, setStats] = useState<Record<string, number>>(rollAllStats);

  // Step 3
  const [selectedBg, setSelectedBg] = useState<Background | null>(null);
  const [alignment, setAlignment] = useState("Neutral");
  const [deity, setDeity] = useState("");

  // Step 4 — locked-in rolled values
  const [rolledHp, setRolledHp] = useState(0);
  const [rolledGp, setRolledGp] = useState(0);
  const [rolledGearSlots, setRolledGearSlots] = useState(10);

  const title = getStartingTitle(charClass, alignment);

  function handleRerollStats() {
    setStats(rollAllStats());
  }

  function advanceToStep(nextStep: number) {
    if (nextStep === 3 && step === 2) {
      setRolledHp(rollStartingHp(charClass, stats.CON));
      setRolledGp(rollStartingGold());
      setRolledGearSlots(startingGearSlots(stats.STR));
    }
    setStep(nextStep);
  }

  async function handleCreate() {
    await onSubmit({
      name: name.trim(),
      class: charClass,
      ancestry,
      alignment,
      background: selectedBg?.name ?? "",
      deity: charClass === "Priest" ? deity : "",
      title,
      hp_max: rolledHp,
      gp: rolledGp,
      stats,
    });
  }

  const reviewRows: [string, string][] = [
    ["Name", name],
    ["Class", charClass],
    ["Ancestry", ancestry],
    ["Alignment", alignment],
    ["Title", title || "—"],
    ["Background", selectedBg?.name ?? "—"],
    ["HP", String(rolledHp)],
    ["Starting Gold", `${rolledGp} gp`],
    ["Gear Slots", String(rolledGearSlots)],
    ...(charClass === "Priest" && deity ? [["Deity", deity] as [string, string]] : []),
  ];

  return (
    <div className={styles.backdrop} onClick={onClose}>
      <div className={styles.dialog} onClick={(e) => e.stopPropagation()}>
        <div className={styles.title}>New Character</div>
        <div className={styles.stepLabel}>{STEP_LABELS[step]}</div>

        <div className={styles.dots}>
          {[0, 1, 2, 3].map((i) => (
            <div
              key={i}
              className={[
                styles.dot,
                i === step ? styles.dotActive : "",
                i < step ? styles.dotDone : "",
              ]
                .filter(Boolean)
                .join(" ")}
            />
          ))}
        </div>

        {/* Step 1 */}
        {step === 0 && (
          <>
            <div className={styles.field}>
              <label className={styles.fieldLabel}>Name</label>
              <input
                className={styles.input}
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                autoFocus
                placeholder="Tharyn the Bold…"
              />
            </div>
            <div className={styles.field}>
              <label className={styles.fieldLabel}>Class</label>
              <SelectDropdown value={charClass} options={CLASSES} onChange={setCharClass} />
            </div>
            <div className={styles.field}>
              <label className={styles.fieldLabel}>Ancestry</label>
              <SelectDropdown value={ancestry} options={ANCESTRIES} onChange={setAncestry} />
            </div>
          </>
        )}

        {/* Step 2 */}
        {step === 1 && (
          <>
            <div className={styles.statGrid}>
              {STAT_NAMES.map((s) => (
                <div key={s} className={styles.statRow}>
                  <span className={styles.statName}>{s}</span>
                  <span className={styles.statValue}>{stats[s]}</span>
                  <span className={styles.statMod}>{formatModifier(getModifier(stats[s]))}</span>
                </div>
              ))}
            </div>
            <button className={styles.rerollBtn} onClick={handleRerollStats}>
              Reroll All
            </button>
          </>
        )}

        {/* Step 3 */}
        {step === 2 && (
          <>
            <div className={styles.field}>
              <label className={styles.fieldLabel}>Background</label>
            </div>
            <div className={styles.bgList}>
              {BACKGROUNDS.map((bg) => (
                <div
                  key={bg.name}
                  className={[
                    styles.bgItem,
                    selectedBg?.name === bg.name ? styles.bgItemSelected : "",
                  ]
                    .filter(Boolean)
                    .join(" ")}
                  onClick={() => setSelectedBg(bg)}
                >
                  <div>{bg.name}</div>
                  {selectedBg?.name === bg.name && (
                    <div className={styles.bgSkill}>{bg.skill}</div>
                  )}
                </div>
              ))}
            </div>
            <button
              className={styles.randomBtn}
              onClick={() =>
                setSelectedBg(BACKGROUNDS[Math.floor(Math.random() * BACKGROUNDS.length)])
              }
            >
              Random Background
            </button>
            <div className={styles.field}>
              <label className={styles.fieldLabel}>Alignment</label>
              <SelectDropdown value={alignment} options={ALIGNMENTS} onChange={setAlignment} />
            </div>
            {charClass === "Priest" && (
              <div className={styles.field}>
                <label className={styles.fieldLabel}>Deity</label>
                <input
                  className={styles.input}
                  type="text"
                  value={deity}
                  onChange={(e) => setDeity(e.target.value)}
                  placeholder="Saint Terragnis…"
                />
              </div>
            )}
          </>
        )}

        {/* Step 4 — Review */}
        {step === 3 && (
          <>
            <div className={styles.reviewSectionTitle}>Character</div>
            <div className={styles.reviewGrid}>
              {reviewRows.map(([label, value]) => (
                <div key={label} className={styles.reviewRow}>
                  <span className={styles.reviewLabel}>{label}</span>
                  <span className={styles.reviewValue}>{value}</span>
                </div>
              ))}
            </div>
            <div className={styles.reviewSectionTitle}>Ability Scores</div>
            <div className={styles.reviewStats}>
              {STAT_NAMES.map((s) => (
                <div key={s} className={styles.reviewStat}>
                  <div className={styles.reviewStatName}>{s}</div>
                  <div className={styles.reviewStatVal}>{stats[s]}</div>
                  <div className={styles.reviewStatMod}>{formatModifier(getModifier(stats[s]))}</div>
                </div>
              ))}
            </div>
          </>
        )}

        <div className={styles.actions}>
          <button
            className={styles.btnSecondary}
            onClick={step === 0 ? onClose : () => setStep(step - 1)}
          >
            {step === 0 ? "Cancel" : "Back"}
          </button>
          {step < 3 ? (
            <button
              className={styles.btnPrimary}
              disabled={step === 0 && !name.trim()}
              onClick={() => advanceToStep(step + 1)}
            >
              Next
            </button>
          ) : (
            <button className={styles.btnPrimary} onClick={handleCreate}>
              Create Character
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
