"use client";

import { useState } from "react";
import { useMutation } from "convex/react";
import { api } from "@/convex/_generated/api";
import { Id } from "@/convex/_generated/dataModel";

interface CreateRoomModalProps {
  spaceId: Id<"spaces">;
  isOpen: boolean;
  onClose: () => void;
  onRoomCreated?: (roomId: Id<"rooms">) => void;
}

export function CreateRoomModal({ spaceId, isOpen, onClose, onRoomCreated }: CreateRoomModalProps) {
  const [name, setName] = useState("");
  const [type, setType] = useState("chat");
  const [backgroundType, setBackgroundType] = useState<"solid" | "gradient" | "image">("solid");
  const [solidColor, setSolidColor] = useState("#1f2937");
  const [gradientStart, setGradientStart] = useState("#1f2937");
  const [gradientEnd, setGradientEnd] = useState("#3b82f6");
  const [imageUrl, setImageUrl] = useState("");
  const [isPrivate, setIsPrivate] = useState(false);
  const [radioPrompt, setRadioPrompt] = useState("");

  const createRoom = useMutation(api.rooms.create);
  const createRadioRoom = useMutation(api.radioRooms.createRadioRoom);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;

    let roomId: Id<"rooms">;

    if (type === "radio") {
      // Create radio room with prompt
      if (!radioPrompt.trim()) {
        alert("Please enter a radio prompt");
        return;
      }
      roomId = await createRadioRoom({
        spaceId,
        name: name.trim(),
        prompt: radioPrompt.trim(),
      });
    } else {
      // Create regular room with background config
      const backgroundConfig = {
        type: backgroundType,
        ...(backgroundType === "solid" && { solidColor }),
        ...(backgroundType === "gradient" && { gradientStart, gradientEnd }),
        ...(backgroundType === "image" && { imageUrl }),
      };

      roomId = await createRoom({
        spaceId,
        name: name.trim(),
        type,
        isPrivate,
        backgroundConfig,
      });
    }

    // Switch to the newly created room before closing
    if (onRoomCreated) {
      onRoomCreated(roomId);
    }

    setName("");
    setType("chat");
    setBackgroundType("solid");
    setSolidColor("#1f2937");
    setGradientStart("#1f2937");
    setGradientEnd("#3b82f6");
    setImageUrl("");
    setIsPrivate(false);
    setRadioPrompt("");
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 max-w-md w-full mx-4">
        <h2 className="text-xl font-bold mb-4">Create New Room</h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">Room Name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="general, music, etc."
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Room Type</label>
            <select
              value={type}
              onChange={(e) => setType(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="chat">Chat</option>
              <option value="canvas">Canvas</option>
              <option value="radio">Radio Station</option>
            </select>
          </div>

          {type === "radio" && (
            <div>
              <label className="block text-sm font-medium mb-1">Radio Prompt</label>
              <textarea
                value={radioPrompt}
                onChange={(e) => setRadioPrompt(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                placeholder="e.g., groovy neosoul jazz songs, or upbeat indie rock with summer vibes"
                rows={3}
                required
              />
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                Describe the type of music you want this radio station to play continuously
              </p>
            </div>
          )}

          {type !== "radio" && (
            <div>
              <label className="block text-sm font-medium mb-2">Background</label>
            <div className="space-y-3">
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={() => setBackgroundType("solid")}
                  className={`px-3 py-1 rounded text-sm ${
                    backgroundType === "solid"
                      ? "bg-blue-600 text-white"
                      : "bg-gray-200 dark:bg-gray-700"
                  }`}
                >
                  Solid
                </button>
                <button
                  type="button"
                  onClick={() => setBackgroundType("gradient")}
                  className={`px-3 py-1 rounded text-sm ${
                    backgroundType === "gradient"
                      ? "bg-blue-600 text-white"
                      : "bg-gray-200 dark:bg-gray-700"
                  }`}
                >
                  Gradient
                </button>
                <button
                  type="button"
                  onClick={() => setBackgroundType("image")}
                  className={`px-3 py-1 rounded text-sm ${
                    backgroundType === "image"
                      ? "bg-blue-600 text-white"
                      : "bg-gray-200 dark:bg-gray-700"
                  }`}
                >
                  Image
                </button>
              </div>

              {backgroundType === "solid" && (
                <div>
                  <label className="block text-xs mb-1">Color</label>
                  <input
                    type="color"
                    value={solidColor}
                    onChange={(e) => setSolidColor(e.target.value)}
                    className="w-full h-10 rounded border border-gray-300 dark:border-gray-600"
                  />
                </div>
              )}

              {backgroundType === "gradient" && (
                <div className="space-y-2">
                  <div>
                    <label className="block text-xs mb-1">Start Color</label>
                    <input
                      type="color"
                      value={gradientStart}
                      onChange={(e) => setGradientStart(e.target.value)}
                      className="w-full h-10 rounded border border-gray-300 dark:border-gray-600"
                    />
                  </div>
                  <div>
                    <label className="block text-xs mb-1">End Color</label>
                    <input
                      type="color"
                      value={gradientEnd}
                      onChange={(e) => setGradientEnd(e.target.value)}
                      className="w-full h-10 rounded border border-gray-300 dark:border-gray-600"
                    />
                  </div>
                </div>
              )}

              {backgroundType === "image" && (
                <div>
                  <label className="block text-xs mb-1">Image URL</label>
                  <input
                    type="url"
                    value={imageUrl}
                    onChange={(e) => setImageUrl(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="https://example.com/image.jpg"
                  />
                </div>
              )}
            </div>
            </div>
          )}

          {type !== "radio" && (
            <div>
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={isPrivate}
                  onChange={(e) => setIsPrivate(e.target.checked)}
                  className="rounded"
                />
                Make room private
              </label>
            </div>
          )}

          <div className="flex gap-3 justify-end pt-4">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded font-medium"
            >
              Create Room
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
