<script lang="ts">
  import { Button, Input } from "$lib/components/ui";
  import { createRoom } from "$lib/matrix";
  import { toasts } from "$lib/stores/ui";
  import { syncRoomsFromEvent, selectRoom } from "$lib/stores/matrix";

  interface Props {
    isOpen: boolean;
    onClose: () => void;
  }

  let { isOpen, onClose }: Props = $props();

  let roomName = $state("");
  let isDirect = $state(false);
  let isCreating = $state(false);

  async function handleCreate() {
    if (!roomName.trim()) {
      toasts.error("Please enter a room name");
      return;
    }

    isCreating = true;

    try {
      const result = await createRoom(roomName.trim(), isDirect);
      toasts.success("Room created!");

      // Add new room to list and select it
      syncRoomsFromEvent("join", result.room_id);
      selectRoom(result.room_id);

      // Reset and close
      roomName = "";
      isDirect = false;
      onClose();
    } catch (e: any) {
      console.error("Failed to create room:", e);
      toasts.error(e.message || "Failed to create room");
    } finally {
      isCreating = false;
    }
  }

  function handleKeyDown(e: KeyboardEvent) {
    if (e.key === "Escape") {
      onClose();
    }
  }
</script>

{#if isOpen}
  <div
    class="fixed inset-0 bg-black/70 flex items-center justify-center z-50"
    onclick={onClose}
    onkeydown={handleKeyDown}
    role="dialog"
    aria-modal="true"
    tabindex="-1"
  >
    <div
      class="bg-dark rounded-2xl p-6 w-full max-w-md mx-4"
      onclick={(e) => e.stopPropagation()}
      role="document"
    >
      <h2 class="text-xl font-semibold text-light mb-4">Create New Room</h2>

      <form
        onsubmit={(e) => {
          e.preventDefault();
          handleCreate();
        }}
        class="flex flex-col gap-4"
      >
        <Input
          bind:value={roomName}
          label="Room Name"
          placeholder="My awesome room"
          required
        />

        <label class="flex items-center gap-3 text-light cursor-pointer">
          <input
            type="checkbox"
            bind:checked={isDirect}
            class="w-4 h-4 rounded border-light/30 bg-night text-primary focus:ring-primary"
          />
          <span>Direct message (private 1:1 chat)</span>
        </label>

        <div class="flex gap-3 justify-end mt-2">
          <Button variant="secondary" onclick={onClose} disabled={isCreating}>
            Cancel
          </Button>
          <Button type="submit" loading={isCreating} disabled={isCreating}>
            {isCreating ? "Creating..." : "Create Room"}
          </Button>
        </div>
      </form>
    </div>
  </div>
{/if}
