import { useState, useEffect, useRef } from "react";
import "./TokenDialog.css";

interface Props {
  defaultColor: string;
  onConfirm: (label: string, color: string) => void;
  onCancel: () => void;
}

export default function TokenDialog({
  defaultColor,
  onConfirm,
  onCancel,
}: Props) {
  const [label, setLabel] = useState("");
  const [color, setColor] = useState(defaultColor);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const name = label.trim();
    if (!name) return;
    onConfirm(name, color);
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "Escape") onCancel();
  }

  return (
    <div
      className="dialog-overlay"
      onClick={onCancel}
      onKeyDown={handleKeyDown}
    >
      <div className="dialog" onClick={(e) => e.stopPropagation()}>
        <h3>Add Token</h3>
        <form onSubmit={handleSubmit}>
          <label>
            Name
            <input
              ref={inputRef}
              type="text"
              placeholder="e.g. Strahd von Zarovich"
              value={label}
              onChange={(e) => setLabel(e.target.value)}
              maxLength={30}
            />
          </label>
          <label>
            Colour
            <input
              type="color"
              value={color}
              onChange={(e) => setColor(e.target.value)}
            />
          </label>
          <div className="dialog-actions">
            <button type="button" onClick={onCancel} className="btn-secondary">
              Cancel
            </button>
            <button
              type="submit"
              className="btn-primary"
              disabled={!label.trim()}
            >
              Place Token
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
