import { useState, useRef, useEffect } from "react";
import type { PublicAccess } from "../types";
import "./NewMapModal.css";

interface Props {
  onClose: () => void;
  onCreate: (name: string, publicAccess: PublicAccess) => Promise<void>;
}

export default function NewMapModal({ onClose, onCreate }: Props) {
  const [name, setName] = useState("");
  const [publicAccess, setPublicAccess] = useState<PublicAccess>("private");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const nameRef = useRef<HTMLInputElement>(null);

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const trimmed = name.trim();
    if (!trimmed) return;
    setLoading(true);
    setError(null);
    try {
      await onCreate(trimmed, publicAccess);
      onClose();
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      setError(msg.replace(/^\d+:\s*/, "").trim() || "Failed to create map");
    } finally {
      setLoading(false);
    }
  }

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

  return (
    <div className="modal-backdrop" onClick={onClose} onKeyDown={handleKeyDown}>
      <div className="modal new-map-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>New Map</h2>
          <button className="modal-close" onClick={onClose} aria-label="Close">
            ✕
          </button>
        </div>

        <form onSubmit={handleSubmit} className="new-map-form-modal">
          <label className="field-label">
            Map Name
            <input
              ref={nameRef}
              type="text"
              placeholder="e.g. Ravenloft"
              value={name}
              onChange={(e) => setName(e.target.value)}
              maxLength={60}
              required
            />
          </label>

          <fieldset className="public-access-fieldset">
            <legend>Visibility</legend>

            <label className="radio-option">
              <input
                type="radio"
                name="public_access"
                value="private"
                checked={publicAccess === "private"}
                onChange={() => setPublicAccess("private")}
              />
              <span className="radio-label">
                <strong>Private</strong>
                <span className="radio-hint">Only you and invited users</span>
              </span>
            </label>

            <label className="radio-option">
              <input
                type="radio"
                name="public_access"
                value="public_view"
                checked={publicAccess === "public_view"}
                onChange={() => setPublicAccess("public_view")}
              />
              <span className="radio-label">
                <strong>Public – View Only</strong>
                <span className="radio-hint">
                  Anyone with the link can view
                </span>
              </span>
            </label>

            <label className="radio-option">
              <input
                type="radio"
                name="public_access"
                value="public_edit"
                checked={publicAccess === "public_edit"}
                onChange={() => setPublicAccess("public_edit")}
              />
              <span className="radio-label">
                <strong>Public – View &amp; Edit</strong>
                <span className="radio-hint">
                  Anyone with the link can view and edit
                </span>
              </span>
            </label>
          </fieldset>

          {error && <p className="form-error">{error}</p>}

          <div className="modal-actions">
            <button type="button" className="btn-secondary" onClick={onClose}>
              Cancel
            </button>
            <button
              type="submit"
              className="btn-primary"
              disabled={!name.trim() || loading}
            >
              {loading ? "Creating…" : "Create Map"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
