import { useState, useRef } from "react";
import socket from "../socket";
import styles from "./DiceButton.module.css";

interface DiceButtonProps {
  campaignId: number;
  characterId?: number;
  characterName?: string;
  characterColor?: string;
  type: "attack" | "ability-check" | "custom";
  dice: string;
  label: string;
  icon?: string;
  title?: string;
  forceCrit?: boolean;
}

export default function DiceButton({
  campaignId,
  characterId,
  characterName,
  characterColor,
  type,
  dice,
  label,
  icon = "🎲",
  title: titleProp,
  forceCrit,
}: DiceButtonProps) {
  const [showMenu, setShowMenu] = useState(false);
  const longPressRef = useRef<ReturnType<typeof setTimeout>>();
  const longPressTriggered = useRef(false);

  function rollWith(advantage: boolean, disadvantage: boolean) {
    setShowMenu(false);

    let actualDice = dice;
    let actualLabel = label;
    let sendAdvantage = advantage && !disadvantage;
    let sendDisadvantage = disadvantage && !advantage;

    const isD20 = dice.toLowerCase().includes("d20");
    if (!isD20 && (advantage || forceCrit)) {
      const match = dice.match(/^(\d*)d(\d+)(.*)/i);
      if (match) {
        const count = match[1] ? parseInt(match[1], 10) : 1;
        actualDice = `${count * 2}d${match[2]}${match[3] || ""}`;
        actualLabel = label + " (CRIT)";
      }
      sendAdvantage = false;
    }

    socket.emit("roll:request", {
      campaignId,
      characterId,
      characterName,
      characterColor,
      type,
      dice: actualDice,
      label: actualLabel,
      advantage: sendAdvantage,
      disadvantage: sendDisadvantage,
    });
  }

  function handleClick(e: React.MouseEvent) {
    if (longPressTriggered.current) {
      longPressTriggered.current = false;
      return;
    }
    const advantage = e.shiftKey;
    const disadvantage = e.ctrlKey || e.metaKey;
    rollWith(advantage, disadvantage);
  }

  function handleTouchStart() {
    longPressTriggered.current = false;
    longPressRef.current = setTimeout(() => {
      longPressTriggered.current = true;
      setShowMenu(true);
    }, 500);
  }

  function handleTouchEnd() {
    if (longPressRef.current) clearTimeout(longPressRef.current);
  }

  function handleTouchMove() {
    if (longPressRef.current) clearTimeout(longPressRef.current);
  }

  return (
    <div className={styles.wrapper}>
      <button
        className={`${styles.btn} ${forceCrit ? styles.crit : ""}`}
        onClick={handleClick}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
        onTouchMove={handleTouchMove}
        title={
          titleProp ||
          `Roll ${dice} (Shift: advantage, Ctrl: disadvantage, long-press on mobile)`
        }
      >
        {icon}
      </button>
      {showMenu && (
        <div className={styles.menu}>
          <button
            className={styles.menuBtn}
            onClick={() => rollWith(false, false)}
          >
            Roll
          </button>
          <button
            className={`${styles.menuBtn} ${styles.menuBtnAdv}`}
            onClick={() => rollWith(true, false)}
          >
            ADV
          </button>
          <button
            className={`${styles.menuBtn} ${styles.menuBtnDis}`}
            onClick={() => rollWith(false, true)}
          >
            DIS
          </button>
        </div>
      )}
    </div>
  );
}
