import { useState } from "react";
import type { RollResult } from "../types";
import socket from "../socket";
import RollEntry from "./RollEntry";
import styles from "./RollLog.module.css";

interface RollLogProps {
  campaignId: number;
  rolls: RollResult[];
  freshIds: Set<number>;
}

type MobileState = "hidden" | "peek" | "open";

export default function RollLog({ campaignId, rolls, freshIds }: RollLogProps) {
  const [collapsed, setCollapsed] = useState(false);
  const [mobileState, setMobileState] = useState<MobileState>("peek");
  const [input, setInput] = useState("");

  function handleRoll(e: React.FormEvent) {
    e.preventDefault();
    if (!input.trim()) return;
    socket.emit("roll:request", {
      campaignId,
      type: "custom",
      dice: input.trim(),
      label: input.trim(),
    });
    setInput("");
  }

  function cycleMobile() {
    setMobileState((prev) => {
      if (prev === "hidden") return "peek";
      if (prev === "peek") return "open";
      return "hidden";
    });
  }

  // Desktop collapsed
  if (collapsed) {
    return (
      <div
        className={`${styles.panel} ${styles.collapsed}`}
        onClick={() => setCollapsed(false)}
      >
        <div className={styles.collapsedContent}>
          <span className={styles.collapsedIcon}>🎲</span>
          {rolls.length > 0 && (
            <span className={styles.collapsedLast}>{rolls[0].total}</span>
          )}
        </div>
      </div>
    );
  }

  const mobileClass =
    mobileState === "hidden"
      ? styles.mobileHidden
      : mobileState === "open"
        ? styles.mobileOpen
        : "";

  return (
    <div className={`${styles.panel} ${mobileClass}`}>
      <div className={styles.header}>
        <span className={styles.title}>Roll Log</span>
        <div className={styles.headerBtns}>
          <button
            className={`${styles.collapseBtn} ${styles.mobileOnly}`}
            onClick={cycleMobile}
          >
            {mobileState === "open" ? "▾" : "▴"}
          </button>
          <button
            className={`${styles.collapseBtn} ${styles.desktopOnly}`}
            onClick={() => setCollapsed(true)}
          >
            ▸
          </button>
        </div>
      </div>
      <div className={styles.inputArea}>
        <form onSubmit={handleRoll}>
          <input
            className={styles.input}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Roll dice... (e.g. 2d6+1)"
          />
        </form>
        <div className={styles.hint}>
          Long-press dice for advantage/disadvantage
        </div>
      </div>
      <div className={styles.entries}>
        {rolls.length === 0 && <p className={styles.empty}>No rolls yet</p>}
        {rolls.map((roll) => (
          <RollEntry key={roll.id} roll={roll} fresh={freshIds.has(roll.id)} />
        ))}
      </div>
    </div>
  );
}
