import { useState } from "react";
import socket from "../socket.js";
import type { Character } from "../types.js";
import styles from "./CombatStartModal.module.css";

interface CombatStartModalProps {
  characters: Character[];
  campaignId: number;
  onClose: () => void;
}

interface EnemyEntry {
  key: number;
  name: string;
  hp_max: string;
}

let enemyKey = 0;

export default function CombatStartModal({
  characters,
  campaignId,
  onClose,
}: CombatStartModalProps) {
  const [label, setLabel] = useState("");
  const [selectedCharIds, setSelectedCharIds] = useState<Set<number>>(
    new Set(characters.map((c) => c.id))
  );
  const [enemies, setEnemies] = useState<EnemyEntry[]>([
    { key: enemyKey++, name: "", hp_max: "" },
  ]);

  function toggleChar(id: number) {
    setSelectedCharIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  }

  function updateEnemy(key: number, field: "name" | "hp_max", value: string) {
    setEnemies((prev) =>
      prev.map((e) => (e.key === key ? { ...e, [field]: value } : e))
    );
  }

  function addEnemyRow() {
    setEnemies((prev) => [...prev, { key: enemyKey++, name: "", hp_max: "" }]);
  }

  function removeEnemyRow(key: number) {
    setEnemies((prev) => prev.filter((e) => e.key !== key));
  }

  function handleStart() {
    const validEnemies = enemies
      .filter((e) => e.name.trim() && parseInt(e.hp_max, 10) > 0)
      .map((e) => ({ name: e.name.trim(), hp_max: parseInt(e.hp_max, 10) }));

    socket.emit("initiative:start", {
      campaignId,
      label: label.trim() || undefined,
      character_ids: Array.from(selectedCharIds),
      enemies: validEnemies,
    });
    onClose();
  }

  const canStart = selectedCharIds.size > 0;

  return (
    <div className={styles.backdrop} onClick={onClose}>
      <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
        <div className={styles.modalHeader}>
          <span className={styles.modalTitle}>Start Combat</span>
          <button className={styles.closeBtn} onClick={onClose}>✕</button>
        </div>

        {/* Optional label */}
        <div className={styles.field}>
          <label className={styles.fieldLabel}>Label (optional)</label>
          <input
            className={styles.input}
            placeholder="e.g. Throne Room"
            value={label}
            onChange={(e) => setLabel(e.target.value)}
          />
        </div>

        {/* Character selection */}
        <div className={styles.field}>
          <label className={styles.fieldLabel}>Party Members</label>
          <div className={styles.charList}>
            {characters.map((c) => (
              <label key={c.id} className={styles.charRow}>
                <input
                  type="checkbox"
                  checked={selectedCharIds.has(c.id)}
                  onChange={() => toggleChar(c.id)}
                />
                <span
                  className={styles.charDot}
                  style={{ background: c.color }}
                />
                <span className={styles.charName}>{c.name}</span>
              </label>
            ))}
          </div>
        </div>

        {/* Enemy entries */}
        <div className={styles.field}>
          <label className={styles.fieldLabel}>Enemies</label>
          {enemies.map((e) => (
            <div key={e.key} className={styles.enemyRow}>
              <input
                className={styles.input}
                placeholder="Name (e.g. Goblin x3)"
                value={e.name}
                onChange={(ev) => updateEnemy(e.key, "name", ev.target.value)}
              />
              <input
                className={`${styles.input} ${styles.hpInput}`}
                placeholder="Max HP"
                type="number"
                min={1}
                value={e.hp_max}
                onChange={(ev) => updateEnemy(e.key, "hp_max", ev.target.value)}
              />
              <button
                className={styles.removeRowBtn}
                onClick={() => removeEnemyRow(e.key)}
                disabled={enemies.length === 1}
              >
                ✕
              </button>
            </div>
          ))}
          <button className={styles.addRowBtn} onClick={addEnemyRow}>
            + Add Another Enemy
          </button>
        </div>

        <div className={styles.actions}>
          <button
            className={styles.startBtn}
            onClick={handleStart}
            disabled={!canStart}
          >
            Roll Initiative ⚔
          </button>
          <button className={styles.cancelBtn} onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}
