import React from "react";
import weaponsFile from "../../data/weapons.yml";
import armorShieldsFile from "../../data/armor_shields.yml";
import { Fields, Bond, CheckMap } from "../types";
import { STATUSES, FEELINGS, MUTUAL_EXCLUSIVE, MARTIAL_ITEMS } from "../constants";

interface MainPageProps {
  isActive: boolean;
  fields: Fields;
  f: <K extends keyof Fields>(key: K, val: Fields[K]) => void;
  level: number;
  setLevel: React.Dispatch<React.SetStateAction<number>>;
  xp: number;
  xpPct: number;
  fp: number;
  setFp: React.Dispatch<React.SetStateAction<number>>;
  fpTotal: number;
  inCrisis: boolean;
  calcHP: () => void;
  calcMP: () => void;
  statuses: CheckMap;
  toggleStatus: (s: string) => void;
  martial: CheckMap;
  toggleMartial: (m: string) => void;
  bonds: Bond[];
  setBonds: React.Dispatch<React.SetStateAction<Bond[]>>;
  toggleFeeling: (bondIdx: number, feeling: string) => void;
  weaponPickerOpen: boolean;
  setWeaponPickerOpen: React.Dispatch<React.SetStateAction<boolean>>;
  weaponCategory: string;
  setWeaponCategory: React.Dispatch<React.SetStateAction<string>>;
}

export default function MainPage({
  isActive,
  fields,
  f,
  level,
  setLevel,
  xp,
  xpPct,
  fp,
  setFp,
  fpTotal,
  inCrisis,
  calcHP,
  calcMP,
  statuses,
  toggleStatus,
  martial,
  toggleMartial,
  bonds,
  setBonds,
  toggleFeeling,
  weaponPickerOpen,
  setWeaponPickerOpen,
  weaponCategory,
  setWeaponCategory,
}: MainPageProps) {
  return (
    <div className={`page${isActive ? " active" : ""}`} id="page-main">
      {/* Row 1: Identity + Level */}
      <div className="grid-2" style={{ marginBottom: 20 }}>
        <div className="section">
          <div className="section-title">
            <span className="icon">✦</span> Identity &amp; Traits
          </div>
          <div className="field-row">
            <div className="field" style={{ flex: 2 }}>
              <label htmlFor="character-name">Name</label>
              <input
                id="character-name"
                type="text"
                value={fields.charName}
                onChange={(e) => f("charName", e.target.value)}
                placeholder="Character name…"
              />
            </div>
            <div className="field">
              <label htmlFor="character-pronouns">Pronouns</label>
              <input
                id="character-pronouns"
                type="text"
                value={fields.charPronouns}
                onChange={(e) => f("charPronouns", e.target.value)}
                placeholder="they/them"
              />
            </div>
          </div>
          <div className="field">
            <label htmlFor="character-identity">Identity</label>
            <input
              id="character-identity"
              type="text"
              value={fields.charIdentity}
              onChange={(e) => f("charIdentity", e.target.value)}
              placeholder="Who are you?"
            />
          </div>
          <div className="field-row">
            <div className="field">
              <label htmlFor="character-theme">Theme</label>
              <input
                id="character-theme"
                type="text"
                value={fields.charTheme}
                onChange={(e) => f("charTheme", e.target.value)}
                placeholder="Your theme…"
              />
            </div>
            <div className="field">
              <label htmlFor="character-origin">Origin</label>
              <input
                id="character-origin"
                type="text"
                value={fields.charOrigin}
                onChange={(e) => f("charOrigin", e.target.value)}
                placeholder="Where from?"
              />
            </div>
          </div>
          <div className="field">
            <label htmlFor="character-traits">Traits (comma-separated)</label>
            <textarea
              id="character-traits"
              value={fields.charTraits}
              onChange={(e) => f("charTraits", e.target.value)}
              placeholder="Brave, Reckless, Loyal to a fault…"
              style={{ minHeight: 55 }}
            />
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="section">
            <div className="section-title">
              <span className="icon">⬡</span> Level &amp; Experience
            </div>
            <div className="grid-2" style={{ gap: 14 }}>
              <div className="level-display">
                <span className="level-num">{level}</span>
                <span className="level-text">Character Level</span>
                <button
                  type="button"
                  className="add-btn"
                  style={{ marginTop: 10, width: "100%", justifyContent: "center" }}
                  onClick={() => setLevel((l) => Math.min(50, l + 1))}
                >
                  + Level Up
                </button>
                <button
                  type="button"
                  className="add-btn"
                  style={{
                    marginTop: 4,
                    width: "100%",
                    justifyContent: "center",
                    borderColor: "var(--border-bright)",
                    color: "var(--text-dim)",
                  }}
                  onClick={() => setLevel((l) => Math.max(1, l - 1))}
                >
                  − Level Down
                </button>
              </div>
              <div>
                <div className="field">
                  <label htmlFor="character-xp-current">Experience Points (XP)</label>
                  <input
                    id="character-xp-current"
                    type="number"
                    value={fields.xpCurrent}
                    onChange={(e) => f("xpCurrent", e.target.value)}
                    min="0"
                  />
                </div>
                <div className="xp-bar-wrap">
                  <div className="xp-bar" style={{ width: xpPct + "%" }} />
                </div>
                <div className="xp-label">
                  <span>{xp} XP</span>
                  <span>10 XP = Level</span>
                </div>
                <div className="field" style={{ marginTop: 12 }}>
                  <label htmlFor="character-zenit">Zenit (currency)</label>
                  <input
                    id="character-zenit"
                    type="number"
                    value={fields.zenit}
                    onChange={(e) => f("zenit", e.target.value)}
                    min="0"
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="section">
            <div className="section-title">
              <span className="icon">⊕</span> Defenses
            </div>
            <div className="def-row">
              <div className="def-block">
                <label htmlFor="character-initiative">Initiative Mod</label>
                <input
                  id="character-initiative"
                  type="number"
                  value={fields.initMod}
                  onChange={(e) => f("initMod", e.target.value)}
                />
              </div>
              <div className="def-block">
                <label htmlFor="character-defense">Defense</label>
                <input
                  id="character-defense"
                  type="number"
                  value={fields.defense}
                  onChange={(e) => f("defense", e.target.value)}
                />
              </div>
              <div className="def-block">
                <label htmlFor="character-magic-defense">Magic Defense</label>
                <input
                  id="character-magic-defense"
                  type="number"
                  value={fields.magDef}
                  onChange={(e) => f("magDef", e.target.value)}
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Row 2: Attributes + Status + Vitals */}
      <div className="grid-3" style={{ marginBottom: 20 }}>
        <div className="section">
          <div className="section-title">
            <span className="icon">◈</span> Attributes
          </div>
          <div className="attr-grid">
            {(
              [
                { label: "Dexterity", base: "dexBase", cur: "dexCur" },
                { label: "Insight", base: "insBase", cur: "insCur" },
                { label: "Might", base: "migBase", cur: "migCur" },
                { label: "Willpower", base: "wlpBase", cur: "wlpCur" },
              ] as const
            ).map(({ label, base, cur }) => (
              <div key={label} className="attr-block">
                <div className="attr-name">{label}</div>
                <div className="attr-inputs">
                  <div style={{ flex: 1 }}>
                    <label style={{ fontSize: "0.48rem" }}>Base</label>
                    <input
                      type="number"
                      value={fields[base]}
                      onChange={(e) => f(base, e.target.value)}
                      min="6"
                      max="12"
                    />
                  </div>
                  <div className="attr-sep">→</div>
                  <div style={{ flex: 1 }}>
                    <label style={{ fontSize: "0.48rem" }}>Current</label>
                    <input
                      type="number"
                      value={fields[cur]}
                      onChange={(e) => f(cur, e.target.value)}
                      min="6"
                      max="12"
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="section">
          <div className="section-title">
            <span className="icon">⚠</span> Status Effects
          </div>
          <div className="status-grid">
            {STATUSES.map((s) => (
              <div
                key={s}
                className={`status-item${statuses[s] ? " active-status" : ""}`}
                onClick={() => toggleStatus(s)}
              >
                <div className="status-check">{statuses[s] ? "✗" : ""}</div>
                <div className="status-label">{s}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="section">
          <div className="section-title">
            <span className="icon">♥</span> Hit, Mind &amp; Inventory Points
          </div>

          <div className="vital-block">
            <div className="vital-label hp">HP</div>
            <div style={{ flex: 1 }}>
              <div className="vital-formula">MIG×5 + Level + Other</div>
              <div className="vital-inputs">
                <input
                  type="number"
                  value={fields.hpCur}
                  onChange={(e) => f("hpCur", e.target.value)}
                  placeholder="Cur"
                />
                <div className="vital-sep">/</div>
                <input
                  type="number"
                  value={fields.hpMax}
                  onChange={(e) => f("hpMax", e.target.value)}
                  placeholder="Max"
                />
                {inCrisis && <div className="crisis-badge">CRISIS</div>}
              </div>
            </div>
            <button
              type="button"
              className="add-btn"
              style={{ padding: "4px 8px" }}
              onClick={calcHP}
              title="Auto-calculate from Might"
            >
              Calc
            </button>
          </div>

          <div className="vital-block">
            <div className="vital-label mp">MP</div>
            <div style={{ flex: 1 }}>
              <div className="vital-formula">WLP×5 + Level + Other</div>
              <div className="vital-inputs">
                <input
                  type="number"
                  value={fields.mpCur}
                  onChange={(e) => f("mpCur", e.target.value)}
                  placeholder="Cur"
                />
                <div className="vital-sep">/</div>
                <input
                  type="number"
                  value={fields.mpMax}
                  onChange={(e) => f("mpMax", e.target.value)}
                  placeholder="Max"
                />
              </div>
            </div>
            <button
              type="button"
              className="add-btn"
              style={{ padding: "4px 8px" }}
              onClick={calcMP}
              title="Auto-calculate from Willpower"
            >
              Calc
            </button>
          </div>

          <div className="vital-block">
            <div className="vital-label ip">IP</div>
            <div style={{ flex: 1 }}>
              <div className="vital-formula">6 + Other</div>
              <div className="vital-inputs">
                <input
                  type="number"
                  value={fields.ipCur}
                  onChange={(e) => f("ipCur", e.target.value)}
                  placeholder="Cur"
                />
                <div className="vital-sep">/</div>
                <input
                  type="number"
                  value={fields.ipMax}
                  onChange={(e) => f("ipMax", e.target.value)}
                  placeholder="Max"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Row 3: FP + Bonds */}
      <div className="grid-2" style={{ marginBottom: 20 }}>
        <div className="section">
          <div className="section-title">
            <span className="icon">✦</span> Fabula Points
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
            <div>
              <label>Current FP</label>
              <input
                type="number"
                value={fp}
                min="0"
                max="20"
                onChange={(e) => setFp(parseInt(e.target.value) || 0)}
                style={{
                  width: 70,
                  textAlign: "center",
                  fontSize: "1.4rem",
                  fontFamily: "var(--font-mono)",
                }}
              />
            </div>
            <div className="fp-pips">
              {Array.from({ length: fpTotal }, (_, i) => (
                <div
                  key={i}
                  className={`fp-pip${i < fp ? " filled" : ""}`}
                  onClick={() => setFp(i < fp ? i : i + 1)}
                />
              ))}
            </div>
          </div>
          <div className="fp-rules">
            <div className="fp-rule">
              <strong>+1 FP</strong> if you have none at start of session.
            </div>
            <div className="fp-rule">
              <strong>+1 FP</strong> when a Villain makes an entrance.
            </div>
            <div className="fp-rule">
              <strong>+1 FP</strong> when you fumble a Check.
            </div>
            <div className="fp-rule">
              <strong>+2 FP</strong> if you surrender at zero HP.
            </div>
            <div className="fp-rule" style={{ marginTop: 6 }}>
              <strong>Spend 1 FP</strong> to invoke a trait: reroll one or both dice.
            </div>
            <div className="fp-rule">
              <strong>Spend 1 FP</strong> to invoke a bond: add its strength to the result.
            </div>
            <div className="fp-rule">
              <strong>Spend 1 FP</strong> to alter the story.
            </div>
          </div>
        </div>

        <div className="section">
          <div className="section-title">
            <span className="icon">⊗</span> Bonds
          </div>
          {bonds.map((bond, idx) => (
            <div key={idx} className="bond-block">
              <div className="bond-header">
                <div className="bond-num">{idx + 1}</div>
                <input
                  type="text"
                  placeholder="Bond target name…"
                  value={bond.name}
                  onChange={(e) =>
                    setBonds((prev) =>
                      prev.map((b, i) => (i === idx ? { ...b, name: e.target.value } : b))
                    )
                  }
                />
              </div>
              <div className="bond-feelings">
                {FEELINGS.map((feeling) => {
                  const isActive = bond.feelings.includes(feeling);
                  const isDisabled =
                    !isActive && bond.feelings.includes(MUTUAL_EXCLUSIVE[feeling]);
                  return (
                    <div
                      key={feeling}
                      className={`bond-feeling${isActive ? " active" : ""}${isDisabled ? " disabled" : ""}`}
                      onClick={() => !isDisabled && toggleFeeling(idx, feeling)}
                    >
                      <div className="bond-feeling-box">{isActive ? "✓" : ""}</div>
                      <span>{feeling}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Row 4: Equipment + Backpack */}
      <div className="grid-2" style={{ marginBottom: 20 }}>
        <div className="section">
          <div className="section-title">
            <span className="icon">⚔</span> Equipment
          </div>
          <div className="martial-row">
            {MARTIAL_ITEMS.map((m) => (
              <div
                key={m}
                className={`martial-item${martial[m] ? " checked" : ""}`}
                onClick={() => toggleMartial(m)}
              >
                <div className="martial-box">{martial[m] ? "✓" : ""}</div>
                <span>{m}</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 14 }}>
            {(
              [
                {
                  slot: "Accessory",
                  name: "accName",
                  desc: "accDesc",
                  namePh: "Item name",
                  descPh: "Description / effect",
                },
                {
                  slot: "Armor",
                  name: "armName",
                  desc: "armDesc",
                  namePh: "Item name",
                  descPh: "Defense bonus / effect",
                },
                {
                  slot: "Main Hand",
                  name: "mhName",
                  desc: "mhDesc",
                  namePh: "Weapon name",
                  descPh: "Damage / effect",
                },
                {
                  slot: "Off-Hand",
                  name: "ohName",
                  desc: "ohDesc",
                  namePh: "Weapon / shield",
                  descPh: "Damage / effect",
                },
              ] as const
            ).map(({ slot, name, desc, namePh, descPh }) => (
              <div key={slot} className="equip-row">
                <div className="equip-slot">{slot}</div>
                <div className="equip-fields">
                  <input
                    type="text"
                    value={fields[name]}
                    onChange={(e) => f(name, e.target.value)}
                    placeholder={namePh}
                  />
                  <input
                    type="text"
                    value={fields[desc]}
                    onChange={(e) => f(desc, e.target.value)}
                    placeholder={descPh}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="section">
          <div className="section-title">
            <span className="icon">◉</span> Backpack &amp; Notes
          </div>
          <textarea
            value={fields.backpack}
            onChange={(e) => f("backpack", e.target.value)}
            placeholder="Items, notes, lore…"
            style={{ minHeight: 200 }}
          />
          <button
            type="button"
            className="add-btn"
            style={{ marginTop: 8 }}
            onClick={() => {
              setWeaponCategory("all");
              setWeaponPickerOpen(true);
            }}
          >
            + Add Equipment
          </button>

          {weaponPickerOpen &&
            (() => {
              const allWeapons = (weaponsFile as WeaponsFile).weapons;
              const allArmorShields = (armorShieldsFile as ArmorShieldsFile).armor_shields;
              type PickerItem =
                | { kind: "weapon"; data: WeaponTemplate }
                | { kind: "armor"; data: ArmorShieldTemplate };
              const allItems: PickerItem[] = [
                ...allWeapons.map((w) => ({ kind: "weapon" as const, data: w })),
                ...allArmorShields.map((a) => ({ kind: "armor" as const, data: a })),
              ];
              const categories = [
                "all",
                ...Array.from(new Set(allItems.map((i) => i.data.category))).sort(),
              ];
              const visible =
                weaponCategory === "all"
                  ? allItems
                  : allItems.filter((i) => i.data.category === weaponCategory);
              const formatLine = (item: PickerItem) => {
                if (item.kind === "weapon") {
                  const w = item.data;
                  return `• ${w.name}: Acc ${w.accuracy}, Dmg ${w.damage}${w.description ? ` | ${w.description}` : ""}${w.cost > 0 ? ` (${w.cost}z)` : ""}`;
                } else {
                  const a = item.data;
                  const init = a.initiative ?? a.initative ?? 0;
                  return `• ${a.name}: DEF ${a.defense}, MDEF ${a.magic_defense}, Init ${init}${a.description ? ` | ${a.description}` : ""}${a.cost > 0 ? ` (${a.cost}z)` : ""}`;
                }
              };
              return (
                <div
                  className="spell-picker-overlay"
                  onClick={() => setWeaponPickerOpen(false)}
                >
                  <div
                    className="spell-picker-modal"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <div className="spell-picker-header">
                      <span>Choose equipment</span>
                      <button
                        type="button"
                        className="spell-picker-close"
                        onClick={() => setWeaponPickerOpen(false)}
                      >
                        ✕
                      </button>
                    </div>
                    <div
                      style={{
                        display: "flex",
                        gap: 6,
                        flexWrap: "wrap",
                        padding: "8px 14px",
                        borderBottom: "1px solid var(--border)",
                      }}
                    >
                      {categories.map((cat) => (
                        <button
                          type="button"
                          key={cat}
                          className={`add-btn${weaponCategory === cat ? " active-filter" : ""}`}
                          style={{
                            padding: "2px 8px",
                            fontSize: "0.65rem",
                            textTransform: "capitalize",
                          }}
                          onClick={() => setWeaponCategory(cat)}
                        >
                          {cat}
                        </button>
                      ))}
                    </div>
                    <ul className="spell-picker-list">
                      {visible.map((item, i) => (
                        <li
                          key={i}
                          className="spell-picker-item"
                          onClick={() => {
                            const line = formatLine(item);
                            f(
                              "backpack",
                              fields.backpack ? fields.backpack + "\n" + line : line,
                            );
                            setWeaponPickerOpen(false);
                          }}
                        >
                          <span className="spell-picker-name">{item.data.name}</span>
                          <span className="spell-picker-class">{item.data.category}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              );
            })()}
        </div>
      </div>
    </div>
  );
}
