<script lang="ts">
  import { Avatar } from "$lib/components/ui";
  import { setRoomName, setRoomTopic, setRoomAvatar } from "$lib/matrix";
  import { toasts } from "$lib/stores/ui";
  import { syncRoomsFromEvent } from "$lib/stores/matrix";
  import type { RoomSummary } from "$lib/matrix/types";

  interface Props {
    room: RoomSummary;
    onClose: () => void;
  }

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

  let name = $state(room.name);
  let topic = $state(room.topic || "");
  let isSaving = $state(false);
  let avatarFile = $state<File | null>(null);
  let avatarPreview = $state<string | null>(null);

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

  function handleAvatarChange(e: Event) {
    const input = e.target as HTMLInputElement;
    const file = input.files?.[0];
    if (file) {
      avatarFile = file;
      avatarPreview = URL.createObjectURL(file);
    }
  }

  async function handleSave() {
    isSaving = true;
    try {
      const promises: Promise<void>[] = [];

      if (name !== room.name) {
        promises.push(setRoomName(room.roomId, name));
      }

      if (topic !== (room.topic || "")) {
        promises.push(setRoomTopic(room.roomId, topic));
      }

      if (avatarFile) {
        promises.push(setRoomAvatar(room.roomId, avatarFile));
      }

      await Promise.all(promises);
      syncRoomsFromEvent("update", room.roomId);
      toasts.success("Room settings updated");
      onClose();
    } catch (e) {
      console.error("Failed to update room settings:", e);
      toasts.error("Failed to update room settings");
    } finally {
      isSaving = false;
    }
  }

  const hasChanges = $derived(
    name !== room.name || topic !== (room.topic || "") || avatarFile !== null,
  );
</script>

<svelte:window onkeydown={handleKeydown} />

<div
  class="fixed inset-0 bg-black/60 flex items-center justify-center z-50"
  role="dialog"
  aria-modal="true"
  aria-labelledby="settings-title"
  tabindex="-1"
>
  <div
    class="bg-dark rounded-2xl p-6 w-full max-w-md mx-4"
    role="document"
    onclick={(e) => e.stopPropagation()}
    onkeydown={(e) => e.stopPropagation()}
  >
    <div class="flex items-center justify-between mb-6">
      <h2 id="settings-title" class="text-xl font-bold text-light">
        Room Settings
      </h2>
      <button
        class="w-8 h-8 flex items-center justify-center text-light/50 hover:text-light hover:bg-light/10 rounded transition-colors"
        onclick={onClose}
        title="Close"
      >
        <svg
          class="w-5 h-5"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
        >
          <line x1="18" y1="6" x2="6" y2="18" />
          <line x1="6" y1="6" x2="18" y2="18" />
        </svg>
      </button>
    </div>

    <!-- Avatar -->
    <div class="flex flex-col items-center mb-6">
      <div class="relative group">
        <Avatar src={avatarPreview || room.avatarUrl} {name} size="xl" />
        <label
          class="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 rounded-full cursor-pointer transition-opacity"
        >
          <svg
            class="w-6 h-6 text-white"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
          >
            <path
              d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"
            />
            <circle cx="12" cy="13" r="4" />
          </svg>
          <input
            type="file"
            accept="image/*"
            class="hidden"
            onchange={handleAvatarChange}
          />
        </label>
      </div>
      <p class="text-xs text-light/40 mt-2">Click to change avatar</p>
    </div>

    <!-- Name -->
    <div class="mb-4">
      <label
        for="room-name"
        class="block text-sm font-medium text-light/60 mb-1"
      >
        Room Name
      </label>
      <input
        id="room-name"
        type="text"
        bind:value={name}
        class="w-full px-4 py-2 bg-night text-light rounded-lg border border-light/20 placeholder:text-light/40 focus:outline-none focus:border-primary"
        placeholder="Enter room name"
      />
    </div>

    <!-- Topic -->
    <div class="mb-6">
      <label
        for="room-topic"
        class="block text-sm font-medium text-light/60 mb-1"
      >
        Topic
      </label>
      <textarea
        id="room-topic"
        bind:value={topic}
        rows="3"
        class="w-full px-4 py-2 bg-night text-light rounded-lg border border-light/20 placeholder:text-light/40 focus:outline-none focus:border-primary resize-none"
        placeholder="What's this room about?"
      ></textarea>
    </div>

    <!-- Actions -->
    <div class="flex gap-3">
      <button
        class="flex-1 px-4 py-2 text-light/60 hover:text-light hover:bg-light/10 rounded-lg transition-colors"
        onclick={onClose}
        disabled={isSaving}
      >
        Cancel
      </button>
      <button
        class="flex-1 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        onclick={handleSave}
        disabled={isSaving || !hasChanges}
      >
        {isSaving ? "Saving..." : "Save Changes"}
      </button>
    </div>
  </div>
</div>
