import { useState, useCallback } from "react";

interface TableEntry {
  min: number;
  max: number;
  result: string;
}

interface RandomTable {
  name: string;
  dice: string;
  entries: TableEntry[];
}

const BUILTIN_TABLES: RandomTable[] = [
  {
    name: "Tavern Names",
    dice: "1d20",
    entries: [
      { min: 1, max: 2, result: "The Rusty Tankard" },
      { min: 3, max: 4, result: "The Sleeping Dragon" },
      { min: 5, max: 6, result: "The Gilded Flask" },
      { min: 7, max: 8, result: "The Blind Beholder" },
      { min: 9, max: 10, result: "The Copper Kettle" },
      { min: 11, max: 12, result: "The Prancing Pony" },
      { min: 13, max: 14, result: "The Wandering Wyvern" },
      { min: 15, max: 16, result: "The Blacksmith's Rest" },
      { min: 17, max: 18, result: "The Tipsy Goblin" },
      { min: 19, max: 20, result: "The Moonlit Hearth" },
    ],
  },
  {
    name: "Weather",
    dice: "1d12",
    entries: [
      { min: 1, max: 2, result: "Clear skies, warm breeze" },
      { min: 3, max: 4, result: "Overcast, cool" },
      { min: 5, max: 6, result: "Light rain, fog in the morning" },
      { min: 7, max: 8, result: "Thunderstorm, heavy rain" },
      { min: 9, max: 10, result: "Strong winds, debris flying" },
      { min: 11, max: 12, result: "Unnatural: green-tinted fog or blood rain" },
    ],
  },
  {
    name: "NPC Quirks",
    dice: "1d10",
    entries: [
      { min: 1, max: 1, result: "Speaks in rhyming couplets" },
      { min: 2, max: 2, result: "Constantly checks over their shoulder" },
      { min: 3, max: 3, result: "Has a pet mouse on their shoulder" },
      { min: 4, max: 4, result: "Insists on being called 'Your Eminence'" },
      { min: 5, max: 5, result: "Smells strongly of cinnamon" },
      { min: 6, max: 6, result: "Never makes eye contact" },
      { min: 7, max: 7, result: "Finishes everyone else's sentences" },
      { min: 8, max: 8, result: "Carries a broken sword and won't say why" },
      { min: 9, max: 9, result: "Laughs at inappropriate moments" },
      { min: 10, max: 10, result: "Writes everything down in a tiny notebook" },
    ],
  },
  {
    name: "Treasure (Low)",
    dice: "1d6",
    entries: [
      { min: 1, max: 1, result: "5d6 copper pieces" },
      { min: 2, max: 2, result: "2d6 silver pieces and a garnet ring" },
      { min: 3, max: 3, result: "1d6 gold pieces and a potion of healing" },
      { min: 4, max: 4, result: "A scroll with a cantrip and 3d6 silver" },
      { min: 5, max: 5, result: "A mundane item of unusual craftsmanship" },
      { min: 6, max: 6, result: "A map fragment leading to a nearby ruin" },
    ],
  },
];

function rollDice(notation: string): number {
  const match = notation.toLowerCase().match(/^(\d+)d(\d+)([+-]\d+)?$/);
  if (!match) return Math.floor(Math.random() * 20) + 1;
  const count = parseInt(match[1]);
  const sides = parseInt(match[2]);
  const modifier = parseInt(match[3] || "0");
  let total = 0;
  for (let i = 0; i < count; i++) {
    total += Math.floor(Math.random() * sides) + 1;
  }
  return total + modifier;
}

interface RollLog {
  tableName: string;
  roll: number;
  result: string;
}

export function RandomTables() {
  const [selected, setSelected] = useState(0);
  const [log, setLog] = useState<RollLog[]>([]);
  const [customRoll, setCustomRoll] = useState<number | null>(null);

  const table = BUILTIN_TABLES[selected];

  const roll = useCallback(() => {
    const rollVal = rollDice(table.dice);
    const entry = table.entries.find((e) => rollVal >= e.min && rollVal <= e.max);
    const result = entry?.result ?? "No result found";
    setLog((prev) => [{ tableName: table.name, roll: rollVal, result }, ...prev].slice(0, 30));
    setCustomRoll(rollVal);
  }, [table]);

  return (
    <div className="flex flex-col gap-2 h-full">
      {/* Table selector */}
      <select
        className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-2 py-1.5 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] text-xs cursor-pointer"
        value={selected}
        onChange={(e) => {
          setSelected(parseInt(e.target.value));
          setCustomRoll(null);
        }}
      >
        {BUILTIN_TABLES.map((t, i) => (
          <option key={t.name} value={i}>
            {t.name} ({t.dice})
          </option>
        ))}
      </select>

      {/* Roll button */}
      <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 {table.dice}
      </button>

      {/* Result */}
      {customRoll !== null && (
        <div className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-3 text-center">
          <div className="font-mono text-2xl font-bold text-[var(--color-gold-bright)]">
            {customRoll}
          </div>
          <div className="text-[var(--color-text-primary)] text-sm mt-1">
            {table.entries.find((e) => customRoll >= e.min && customRoll <= e.max)?.result}
          </div>
        </div>
      )}

      {/* Table preview */}
      <div className="flex-1 overflow-y-auto">
        <div className="flex flex-col gap-0.5">
          {table.entries.map((e) => (
            <div
              key={`${e.min}-${e.max}`}
              className={`flex items-center gap-2 rounded px-2 py-0.5 text-xs ${
                customRoll !== null && customRoll >= e.min && customRoll <= e.max
                  ? "bg-[var(--color-gold-glow)] text-[var(--color-gold-bright)]"
                  : "text-[var(--color-text-secondary)]"
              }`}
            >
              <span className="font-mono w-8 text-right shrink-0">{e.min === e.max ? e.min : `${e.min}-${e.max}`}</span>
              <span className="truncate">{e.result}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Roll history */}
      {log.length > 0 && (
        <div className="border-t border-[var(--color-border-subtle)] pt-2 max-h-24 overflow-y-auto">
          <div className="text-[10px] font-medium text-[var(--color-text-dim)] mb-1">History</div>
          {log.map((l, i) => (
            <div key={i} className="flex items-center gap-2 text-[10px] py-0.5">
              <span className="text-[var(--color-text-dim)]">{l.tableName}</span>
              <span className="font-mono text-[var(--color-gold-bright)]">{l.roll}</span>
              <span className="text-[var(--color-text-secondary)] truncate">{l.result}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}