import type { Stat } from "../types";
import { getModifier, formatModifier } from "../utils/modifiers";
import InlineNumber from "./InlineNumber";
import DiceButton from "./DiceButton";
import styles from "./StatBlock.module.css";

const STAT_ORDER = ["STR", "DEX", "CON", "INT", "WIS", "CHA"];

interface StatBlockProps {
  stats: Stat[];
  statBonuses?: Map<string, number>;
  onStatChange: (statName: string, newValue: number) => void;
  mode?: "view" | "edit";
  campaignId?: number;
  characterId?: number;
  characterName?: string;
  characterColor?: string;
}

export default function StatBlock({
  stats,
  statBonuses,
  onStatChange,
  mode = "view",
  campaignId,
  characterId,
  characterName,
  characterColor,
}: StatBlockProps) {
  const statMap = new Map(stats.map((s) => [s.stat_name, s.value]));

  return (
    <div className={styles.statGrid}>
      {STAT_ORDER.map((name) => {
        const baseValue = statMap.get(name) ?? 10;
        const bonus = statBonuses?.get(name) ?? 0;
        const value = baseValue + bonus;
        const mod = getModifier(value);
        return (
          <div key={name} className={styles.stat}>
            <span className={styles.statName}>{name}</span>
            <div className={styles.statRow}>
              <span className={styles.modifier}>{formatModifier(mod)}</span>
              {mode === "view" && campaignId && (
                <DiceButton
                  campaignId={campaignId}
                  characterId={characterId}
                  characterName={characterName}
                  characterColor={characterColor}
                  type="ability-check"
                  dice={`1d20${mod >= 0 ? "+" + mod : String(mod)}`}
                  label={`${name} check`}
                />
              )}
            </div>
            <span className={styles.score}>
              {mode === "edit" ? (
                <InlineNumber
                  value={baseValue}
                  onChange={(v) => onStatChange(name, v)}
                  min={1}
                  max={30}
                />
              ) : (
                value
              )}
              {bonus > 0 && <span className={styles.bonus}> (+{bonus})</span>}
            </span>
          </div>
        );
      })}
    </div>
  );
}
