import { useState } from "react";
import styles from "./HpDisplay.module.css";

interface HpDisplayProps {
  current: number;
  max: number;
  onChange: (newCurrent: number) => void;
}

export default function HpDisplay({ current, max, onChange }: HpDisplayProps) {
  const [mode, setMode] = useState<"idle" | "heal" | "damage">("idle");
  const [amount, setAmount] = useState("");

  const ratio = max > 0 ? current / max : 1;
  const colorClass =
    ratio <= 0.25 ? styles.critical : ratio <= 0.5 ? styles.hurt : "";

  function apply() {
    const num = parseInt(amount, 10);
    if (isNaN(num) || num <= 0) {
      reset();
      return;
    }
    if (mode === "heal") {
      onChange(Math.min(current + num, max));
    } else if (mode === "damage") {
      onChange(current - num);
    }
    reset();
  }

  function reset() {
    setMode("idle");
    setAmount("");
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "Enter") apply();
    if (e.key === "Escape") reset();
  }

  return (
    <div className={styles.container}>
      <div className={styles.values}>
        <span className={`${styles.current} ${colorClass}`}>{current}</span>
        <span className={styles.slash}>/</span>
        <span className={styles.max}>{max}</span>
      </div>
      <div className={styles.label}>HP</div>
      {mode === "idle" ? (
        <div className={styles.buttons}>
          <button className={styles.healBtn} onClick={() => setMode("heal")}>
            Heal
          </button>
          <button className={styles.dmgBtn} onClick={() => setMode("damage")}>
            Dmg
          </button>
        </div>
      ) : (
        <div className={styles.inputRow}>
          <input
            className={`${styles.amountInput} ${mode === "heal" ? styles.healing : styles.damage}`}
            type="number"
            min={1}
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="#"
            autoFocus
          />
          <button
            className={`${styles.applyBtn} ${mode === "heal" ? styles.healing : styles.damage}`}
            onClick={apply}
          >
            {mode === "heal" ? "+" : "−"}
          </button>
          <button className={styles.cancelBtn} onClick={reset}>
            ✕
          </button>
        </div>
      )}
    </div>
  );
}
