import { useState, useCallback } from "react";

interface DieResult {
  notation: string;
  rolls: number[];
  total: number;
}

const PRESETS = ["d4", "d6", "d8", "d10", "d12", "d20", "d100"];

function rollDie(sides: number): number {
  return Math.floor(Math.random() * sides) + 1;
}

function parseNotation(notation: string): { count: number; sides: number; modifier: number } | null {
  const match = notation.trim().toLowerCase().match(/^(\d+)?d(\d+)([+-]\d+)?$/);
  if (!match) return null;
  return {
    count: parseInt(match[1] || "1"),
    sides: parseInt(match[2]),
    modifier: parseInt(match[3] || "0"),
  };
}

export function DiceRoller() {
  const [input, setInput] = useState("1d20");
  const [results, setResults] = useState<DieResult[]>([]);
  const [lastTotal, setLastTotal] = useState<number | null>(null);

  const roll = useCallback(() => {
    const parsed = parseNotation(input);
    if (!parsed || parsed.sides < 2 || parsed.count > 100) return;

    const rolls = Array.from({ length: parsed.count }, () => rollDie(parsed.sides));
    const sum = rolls.reduce((a, b) => a + b, 0) + parsed.modifier;
    const result: DieResult = {
      notation: input.trim(),
      rolls,
      total: sum,
    };

    setResults((prev) => [result, ...prev].slice(0, 50));
    setLastTotal(sum);
  }, [input]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") roll();
  };

  return (
    <div className="flex flex-col gap-3 h-full">
      {/* Big result display */}
      <div className="flex items-center justify-center py-3">
        <span className="font-mono text-3xl font-bold text-[var(--color-gold-bright)]">
          {lastTotal !== null ? lastTotal : "—"}
        </span>
      </div>

      {/* Input row */}
      <div className="flex gap-2">
        <input
          className="flex-1 rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-3 py-2 text-[var(--color-text-primary)] placeholder-[var(--color-text-dim)] focus:outline-none focus:border-[var(--color-gold-bright)] text-sm font-mono"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="2d6+3"
        />
        <button
          onClick={roll}
          className="rounded-lg bg-[var(--color-gold-bright)] text-[var(--color-bg-deep)] px-4 py-2 text-sm font-semibold hover:bg-[var(--color-gold-muted)] transition-colors cursor-pointer"
        >
          Roll
        </button>
      </div>

      {/* Quick dice */}
      <div className="flex flex-wrap gap-1.5">
        {PRESETS.map((d) => (
          <button
            key={d}
            onClick={() => {
              const parsed = parseNotation(`1${d}`);
              if (!parsed) return;
              const rolls = [rollDie(parsed.sides)];
              const total = rolls[0] + parsed.modifier;
              setResults((prev) => [{ notation: `1${d}`, rolls, total }, ...prev].slice(0, 50));
              setLastTotal(total);
            }}
            className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-3 py-1 text-xs text-[var(--color-text-secondary)] hover:border-[var(--color-gold-bright)] hover:text-[var(--color-gold-bright)] transition-colors cursor-pointer font-mono"
          >
            {d}
          </button>
        ))}
      </div>

      {/* History */}
      <div className="flex-1 overflow-y-auto">
        <div className="flex flex-col gap-1">
          {results.map((r, i) => (
            <div
              key={i}
              className="flex items-center justify-between rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-subtle)] px-3 py-1.5"
            >
              <span className="font-mono text-xs text-[var(--color-text-secondary)]">
                {r.notation}
                {r.rolls.length > 1 && ` [${r.rolls.join(", ")}]`}
              </span>
              <span className="font-mono text-sm font-bold text-[var(--color-gold-bright)]">
                {r.total}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}