"use client";

import { useEffect, useState, useRef } from "react";
import { Command } from "cmdk";
import { useRouter } from "next/navigation";
import { useQuery } from "convex/react";
import { api } from "@/convex/_generated/api";
import { Id } from "@/convex/_generated/dataModel";
import { Hash, Home, Library, Loader2 } from "lucide-react";

interface QuickSwitcherProps {
  isOpen: boolean;
  onClose: () => void;
  currentSpaceId?: Id<"spaces">;
}

export function QuickSwitcher({ isOpen, onClose, currentSpaceId }: QuickSwitcherProps) {
  const router = useRouter();
  const [search, setSearch] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  // Fetch all spaces
  const spaces = useQuery(api.spaces.list);

  // Fetch rooms for current space
  const rooms = useQuery(
    api.rooms.list,
    currentSpaceId ? { spaceId: currentSpaceId } : "skip"
  );

  // Reset search and autofocus input when opening
  useEffect(() => {
    if (isOpen) {
      setSearch("");
      // Use setTimeout to ensure the input is rendered before focusing
      setTimeout(() => {
        inputRef.current?.focus();
      }, 0);
    }
  }, [isOpen]);

  // Handle keyboard shortcuts
  useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        onClose();
      }
    };

    document.addEventListener("keydown", down);
    return () => document.removeEventListener("keydown", down);
  }, [onClose]);

  const handleSelect = (callback: () => void) => {
    callback();
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-[20vh] bg-black/50 backdrop-blur-sm">
      <Command
        className="w-full max-w-2xl overflow-hidden rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-2xl"
        onKeyDown={(e) => {
          if (e.key === "Escape") {
            e.preventDefault();
            onClose();
          }
        }}
      >
        <div className="flex items-center border-b border-gray-200 dark:border-gray-700 px-4">
          <Command.Input
            ref={inputRef}
            value={search}
            onValueChange={setSearch}
            placeholder="Search spaces, rooms, library..."
            className="flex-1 py-4 text-base bg-transparent outline-none placeholder:text-gray-400 dark:placeholder:text-gray-500"
          />
        </div>

        <Command.List className="max-h-[400px] overflow-y-auto p-2">
          <Command.Empty className="py-6 text-center text-sm text-gray-500">
            No results found.
          </Command.Empty>

          {/* Dashboard/Library */}
          <Command.Group heading="Quick Actions" className="mb-2">
            <Command.Item
              value="dashboard-home"
              onSelect={() => handleSelect(() => router.push("/dashboard"))}
              className="flex items-center gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 aria-selected:bg-gray-100 dark:aria-selected:bg-gray-700"
            >
              <Home className="w-4 h-4 text-gray-500" />
              <div className="flex-1">
                <div className="font-medium text-sm">Dashboard</div>
                <div className="text-xs text-gray-500">View all spaces</div>
              </div>
            </Command.Item>
            <Command.Item
              value="library"
              onSelect={() => handleSelect(() => router.push("/library"))}
              className="flex items-center gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 aria-selected:bg-gray-100 dark:aria-selected:bg-gray-700"
            >
              <Library className="w-4 h-4 text-gray-500" />
              <div className="flex-1">
                <div className="font-medium text-sm">Library</div>
                <div className="text-xs text-gray-500">Your music collection</div>
              </div>
            </Command.Item>
          </Command.Group>

          {/* Spaces */}
          {spaces && spaces.length > 0 && (
            <Command.Group heading="Spaces" className="mb-2">
              {spaces.map((space) => (
                <Command.Item
                  key={space._id}
                  value={`space-${space.name}`}
                  onSelect={() => handleSelect(() => router.push(`/space/${space._id}`))}
                  className="flex items-center gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 aria-selected:bg-gray-100 dark:aria-selected:bg-gray-700"
                >
                  <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-400 to-purple-500 flex items-center justify-center flex-shrink-0">
                    <span className="text-white text-xs font-bold">
                      {space.name.charAt(0).toUpperCase()}
                    </span>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-sm truncate">{space.name}</div>
                    {space.isHomeSpace && (
                      <div className="text-xs text-gray-500">🏠 Home Space</div>
                    )}
                  </div>
                </Command.Item>
              ))}
            </Command.Group>
          )}

          {/* Rooms in current space */}
          {currentSpaceId && rooms && rooms.length > 0 && (
            <Command.Group heading="Rooms in Current Space" className="mb-2">
              {rooms.map((room) => (
                <Command.Item
                  key={room._id}
                  value={`room-${room.name}`}
                  onSelect={() =>
                    handleSelect(() => router.push(`/space/${currentSpaceId}?room=${room._id}`))
                  }
                  className="flex items-center gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 aria-selected:bg-gray-100 dark:aria-selected:bg-gray-700"
                >
                  <Hash className="w-4 h-4 text-gray-500 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-sm truncate">{room.name}</div>
                    <div className="text-xs text-gray-500 capitalize">{room.type}</div>
                  </div>
                  {room.isPrivate && (
                    <div className="text-xs text-gray-500">🔒 Private</div>
                  )}
                </Command.Item>
              ))}
            </Command.Group>
          )}

          {/* Loading state */}
          {!spaces && (
            <div className="py-6 text-center text-sm text-gray-500 flex items-center justify-center gap-2">
              <Loader2 className="w-4 h-4 animate-spin" />
              Loading...
            </div>
          )}
        </Command.List>

        <div className="border-t border-gray-200 dark:border-gray-700 px-4 py-2 text-xs text-gray-500 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 text-xs font-semibold text-gray-800 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded">
                ↑↓
              </kbd>
              <span>Navigate</span>
            </div>
            <div className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 text-xs font-semibold text-gray-800 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded">
                Enter
              </kbd>
              <span>Select</span>
            </div>
            <div className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 text-xs font-semibold text-gray-800 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded">
                Esc
              </kbd>
              <span>Close</span>
            </div>
          </div>
        </div>
      </Command>
    </div>
  );
}
