import { useState } from "react";
import type { Gear, GameItem } from "../types";
import ItemPicker from "./ItemPicker";
import CurrencyRow from "./CurrencyRow";
import SelectDropdown from "./SelectDropdown";
import styles from "./GearList.module.css";

interface GearListProps {
  gear: Gear[];
  gp: number;
  sp: number;
  cp: number;
  slotsUsed: number;
  slotsMax: number;
  onAddFromItem: (item: GameItem) => void;
  onAddCustom: (data: {
    name: string;
    type: string;
    slot_count: number;
  }) => void;
  onRemove: (gearId: number) => void;
  onCurrencyChange: (field: "gp" | "sp" | "cp", value: number) => void;
  mode?: "view" | "edit";
}

function gearIcon(type: string): string {
  switch (type) {
    case "weapon":
      return "⚔";
    case "armor":
      return "🛡";
    case "spell":
      return "✨";
    default:
      return "⚙";
  }
}

export default function GearList({
  gear,
  gp,
  sp,
  cp,
  slotsUsed,
  slotsMax,
  onAddFromItem,
  onAddCustom,
  onRemove,
  onCurrencyChange,
  mode = "view",
}: GearListProps) {
  const [showPicker, setShowPicker] = useState(false);
  const [showCustom, setShowCustom] = useState(false);
  const [customName, setCustomName] = useState("");
  const [customType, setCustomType] = useState("gear");

  function handleCustomAdd(e: React.FormEvent) {
    e.preventDefault();
    if (!customName.trim()) return;
    onAddCustom({ name: customName.trim(), type: customType, slot_count: 1 });
    setCustomName("");
    setShowCustom(false);
  }

  function handleItemSelect(item: GameItem) {
    onAddFromItem(item);
    setShowPicker(false);
  }

  const slotClass =
    slotsUsed >= slotsMax
      ? styles.over
      : slotsUsed >= slotsMax - 2
        ? styles.warning
        : styles.normal;

  return (
    <div className={styles.section}>
      <div className={styles.header}>
        <span className={styles.title}>Gear & Inventory</span>
        <span className={`${styles.slotCounter} ${slotClass}`}>
          Slots: {slotsUsed} / {slotsMax}
        </span>
      </div>

      {gear.length === 0 ? (
        <p className={styles.empty}>No gear yet</p>
      ) : (
        <table className={styles.table}>
          <thead>
            <tr>
              <th className={styles.tableHeader}>Item</th>
              <th className={`${styles.tableHeader} ${styles.center}`}>Type</th>
              <th className={`${styles.tableHeader} ${styles.center}`}>
                Slots
              </th>
              <th className={`${styles.tableHeader} ${styles.right}`}></th>
            </tr>
          </thead>
          <tbody>
            {gear.map((item) => (
              <tr key={item.id} className={styles.row}>
                <td className={styles.cell}>
                  <span className={styles.itemName}>{item.name}</span>
                </td>
                <td className={`${styles.cell} ${styles.center}`}>
                  <span title={item.type}>{gearIcon(item.type)}</span>
                </td>
                <td className={`${styles.cell} ${styles.center}`}>
                  {item.slot_count > 0 ? item.slot_count : "—"}
                </td>
                <td className={`${styles.cell} ${styles.right}`}>
                  {mode === "edit" && (
                    <button
                      className={styles.removeBtn}
                      onClick={() => onRemove(item.id)}
                      title="Remove"
                    >
                      ✕
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      <CurrencyRow gp={gp} sp={sp} cp={cp} onChange={onCurrencyChange} />

      {mode === "edit" && (
        <div className={styles.addArea}>
          {showPicker ? (
            <ItemPicker
              onSelect={handleItemSelect}
              onCustom={() => {
                setShowPicker(false);
                setShowCustom(true);
              }}
              onClose={() => setShowPicker(false)}
            />
          ) : showCustom ? (
            <form className={styles.customForm} onSubmit={handleCustomAdd}>
              <input
                className={styles.customInput}
                type="text"
                placeholder="Item name..."
                value={customName}
                onChange={(e) => setCustomName(e.target.value)}
                autoFocus
              />
              <SelectDropdown
                value={customType.charAt(0).toUpperCase() + customType.slice(1)}
                options={["Weapon", "Armor", "Gear", "Spell"]}
                onChange={(v) => setCustomType(v.toLowerCase())}
              />
              <button className={styles.addBtn} type="submit">
                Add
              </button>
              <button
                className={styles.cancelBtn}
                type="button"
                onClick={() => setShowCustom(false)}
              >
                Cancel
              </button>
            </form>
          ) : (
            <button
              className={styles.addBtn}
              onClick={() => setShowPicker(true)}
            >
              + Add Gear
            </button>
          )}
        </div>
      )}
    </div>
  );
}
