import { useState, useCallback } from "react";

interface Combatant {
  id: string;
  name: string;
  initiative: number;
  hp: number;
  maxHp: number;
  conditions: string[];
}

const CONDITIONS = [
  "Blinded", "Charmed", "Deafened", "Frightened", "Grappled",
  "Incapacitated", "Invisible", "Paralyzed", "Poisoned", "Prone",
  "Restrained", "Stunned", "Unconscious",
];

let nextId = 1;

export function InitiativeTracker() {
  const [combatants, setCombatants] = useState<Combatant[]>([]);
  const [name, setName] = useState("");
  const [initBonus, setInitBonus] = useState(0);
  const [hp, setHp] = useState(10);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [round, setRound] = useState(1);

  const addCombatant = useCallback(() => {
    if (!name.trim()) return;
    const roll = Math.floor(Math.random() * 20) + 1 + initBonus;
    const c: Combatant = {
      id: String(nextId++),
      name: name.trim(),
      initiative: roll,
      hp,
      maxHp: hp,
      conditions: [],
    };
    setCombatants((prev) => [...prev, c].sort((a, b) => b.initiative - a.initiative));
    setName("");
  }, [name, initBonus, hp]);

  const removeCombatant = useCallback((id: string) => {
    setCombatants((prev) => prev.filter((c) => c.id !== id));
    setActiveId((prev) => (prev === id ? null : prev));
  }, []);

  const toggleCondition = useCallback((id: string, condition: string) => {
    setCombatants((prev) =>
      prev.map((c) =>
        c.id === id
          ? {
              ...c,
              conditions: c.conditions.includes(condition)
                ? c.conditions.filter((cn) => cn !== condition)
                : [...c.conditions, condition],
            }
          : c
      )
    );
  }, []);

  const changeHp = useCallback((id: string, delta: number) => {
    setCombatants((prev) =>
      prev.map((c) =>
        c.id === id ? { ...c, hp: Math.max(0, Math.min(c.maxHp, c.hp + delta)) } : c
      )
    );
  }, []);

  const nextTurn = useCallback(() => {
    if (combatants.length === 0) return;
    if (!activeId) {
      setActiveId(combatants[0].id);
      return;
    }
    const idx = combatants.findIndex((c) => c.id === activeId);
    if (idx === combatants.length - 1) {
      setRound((r) => r + 1);
      setActiveId(combatants[0].id);
    } else {
      setActiveId(combatants[idx + 1].id);
    }
  }, [combatants, activeId]);

  const reset = useCallback(() => {
    setCombatants([]);
    setActiveId(null);
    setRound(1);
  }, []);

  return (
    <div className="flex flex-col gap-2 h-full overflow-y-auto">
      {/* Round indicator */}
      <div className="flex items-center justify-between">
        <span className="text-[var(--color-gold-bright)] font-heading text-xs font-semibold">
          Round {round}
        </span>
        <div className="flex gap-1">
          <button
            onClick={nextTurn}
            className="rounded bg-[var(--color-gold-bright)] text-[var(--color-bg-deep)] px-2 py-0.5 text-xs font-semibold cursor-pointer hover:bg-[var(--color-gold-muted)] transition-colors"
          >
            Next Turn
          </button>
          <button
            onClick={reset}
            className="rounded bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] text-[var(--color-text-dim)] px-2 py-0.5 text-xs cursor-pointer hover:text-[var(--color-danger)] transition-colors"
          >
            Reset
          </button>
        </div>
      </div>

      {/* Add combatant */}
      <div className="flex gap-1.5">
        <input
          className="flex-1 min-w-0 rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-2 py-1 text-[var(--color-text-primary)] placeholder-[var(--color-text-dim)] focus:outline-none focus:border-[var(--color-gold-bright)] text-xs"
          value={name}
          onChange={(e) => setName(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && addCombatant()}
          placeholder="Name"
        />
        <input
          className="w-10 rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-1 py-1 text-center text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] text-xs font-mono"
          type="number"
          value={initBonus}
          onChange={(e) => setInitBonus(parseInt(e.target.value) || 0)}
          title="Initiative bonus"
        />
        <input
          className="w-12 rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-1 py-1 text-center text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] text-xs font-mono"
          type="number"
          value={hp}
          onChange={(e) => setHp(parseInt(e.target.value) || 1)}
          title="Max HP"
        />
        <button
          onClick={addCombatant}
          className="rounded-lg bg-[var(--color-gold-bright)] text-[var(--color-bg-deep)] px-2 py-1 text-xs font-semibold cursor-pointer hover:bg-[var(--color-gold-muted)] transition-colors"
        >
          +
        </button>
      </div>

      {/* Combatant list */}
      <div className="flex flex-col gap-1 flex-1 overflow-y-auto">
        {combatants.map((c) => {
          const isActive = c.id === activeId;
          const hpPct = c.maxHp > 0 ? c.hp / c.maxHp : 0;
          const hpColor =
            hpPct > 0.5
              ? "var(--color-success)"
              : hpPct > 0.25
                ? "var(--color-gold-bright)"
                : "var(--color-danger)";

          return (
            <div
              key={c.id}
              className={`rounded-lg p-2 text-xs transition-all cursor-default ${
                isActive
                  ? "glass-card-active"
                  : "bg-[var(--color-bg-surface)] border border-[var(--color-border-subtle)]"
              }`}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 min-w-0">
                  <span className="font-mono text-[var(--color-text-dim)] w-6 text-right shrink-0">
                    {c.initiative}
                  </span>
                  <span className="text-[var(--color-text-primary)] truncate font-medium">
                    {c.name}
                  </span>
                </div>
                <button
                  onClick={() => removeCombatant(c.id)}
                  className="text-[var(--color-text-dim)] hover:text-[var(--color-danger)] transition-colors shrink-0 cursor-pointer"
                  title="Remove"
                >
                  ×
                </button>
              </div>

              {/* HP bar */}
              <div className="flex items-center gap-1.5 mt-1">
                <div className="flex-1 h-1.5 rounded-full bg-[var(--color-bg-deep)] overflow-hidden">
                  <div
                    className="h-full rounded-full transition-all duration-300"
                    style={{ width: `${hpPct * 100}%`, backgroundColor: hpColor }}
                  />
                </div>
                <span className="font-mono text-[10px] shrink-0" style={{ color: hpColor }}>
                  {c.hp}/{c.maxHp}
                </span>
                <button onClick={() => changeHp(c.id, -1)} className="text-[var(--color-text-dim)] hover:text-[var(--color-danger)] cursor-pointer">−</button>
                <button onClick={() => changeHp(c.id, 1)} className="text-[var(--color-text-dim)] hover:text-[var(--color-success)] cursor-pointer">+</button>
              </div>

              {/* Conditions */}
              {c.conditions.length > 0 && (
                <div className="flex flex-wrap gap-0.5 mt-1">
                  {c.conditions.map((cn) => (
                    <span
                      key={cn}
                      onClick={() => toggleCondition(c.id, cn)}
                      className="rounded-full bg-[var(--color-gold-glow)] text-[var(--color-gold-bright)] px-1.5 py-0 text-[10px] cursor-pointer hover:opacity-80"
                    >
                      {cn}
                    </span>
                  ))}
                </div>
              )}

              {/* Add condition */}
              <div className="flex flex-wrap gap-0.5 mt-1">
                {CONDITIONS.filter((cn) => !c.conditions.includes(cn)).slice(0, 5).map((cn) => (
                  <button
                    key={cn}
                    onClick={() => toggleCondition(c.id, cn)}
                    className="rounded bg-[var(--color-bg-deep)] text-[var(--color-text-dim)] px-1 py-0 text-[9px] hover:text-[var(--color-text-secondary)] cursor-pointer transition-colors"
                  >
                    +{cn.slice(0, 3)}
                  </button>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}