"use client";

import { useEffect, useState, useRef } from "react";
import { getChannels, Channel, search } from "@/lib/api";
import { Search, Hash, Lock, FileText, User, Command, ArrowRight } from "lucide-react";

interface CommandPaletteProps {
  open: boolean;
  onClose: () => void;
  onChannelSelect?: (channel: Channel) => void;
}

interface PaletteItem {
  id: string;
  label: string;
  type: "channel" | "dm" | "file" | "command";
  icon: typeof Hash;
  data?: any;
}

export function CommandPalette({ open, onClose, onChannelSelect }: CommandPaletteProps) {
  const [query, setQuery] = useState("");
  const [channels, setChannels] = useState<Channel[]>([]);
  const [searchResults, setSearchResults] = useState<any>(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const debounceRef = useRef<NodeJS.Timeout | null>(null);

  // Load channels on mount
  useEffect(() => {
    getChannels().then(setChannels).catch(() => {});
  }, []);

  // Focus input when opened
  useEffect(() => {
    if (open) {
      setTimeout(() => inputRef.current?.focus(), 50);
      setQuery("");
      setActiveIndex(0);
    }
  }, [open]);

  // Debounced search
  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (!query.trim()) {
      setSearchResults(null);
      return;
    }
    debounceRef.current = setTimeout(async () => {
      try {
        const data = await search(query.trim());
        setSearchResults(data || {});
      } catch {
        setSearchResults(null);
      }
    }, 200);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [query]);

  // Build items list
  const items: PaletteItem[] = [];

  // Commands always shown
  const commands = [
    { id: "cmd-settings", label: "Go to Settings", type: "command" as const, icon: Command },
    { id: "cmd-saved", label: "View Saved Items", type: "command" as const, icon: Command },
    { id: "cmd-status", label: "Set Custom Status", type: "command" as const, icon: Command },
  ];

  if (!query.trim()) {
    // Show channels + commands when no query
    channels.forEach((ch) => {
      items.push({
        id: ch.id,
        label: ch.name,
        type: "channel",
        icon: ch.is_private ? Lock : Hash,
        data: ch,
      });
    });
    items.push(...commands);
  } else {
    // Filter channels by query
    channels
      .filter((ch) => ch.name.toLowerCase().includes(query.toLowerCase()))
      .forEach((ch) => {
        items.push({
          id: ch.id,
          label: ch.name,
          type: "channel",
          icon: ch.is_private ? Lock : Hash,
          data: ch,
        });
      });

    // Add search results
    if (searchResults?.people) {
      searchResults.people.slice(0, 3).forEach((p: any) => {
        items.push({
          id: p.id,
          label: p.name || p.email || "Unknown",
          type: "dm",
          icon: User,
          data: p,
        });
      });
    }
    if (searchResults?.files) {
      searchResults.files.slice(0, 3).forEach((f: any) => {
        items.push({
          id: f.id,
          label: f.name || f.filename || "File",
          type: "file",
          icon: FileText,
          data: f,
        });
      });
    }

    // Add matching commands
    commands
      .filter((c) => c.label.toLowerCase().includes(query.toLowerCase()))
      .forEach((c) => items.push(c));
  }

  // Handle keyboard navigation
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveIndex((i) => Math.min(i + 1, items.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIndex((i) => Math.max(i - 1, 0));
    } else if (e.key === "Enter") {
      e.preventDefault();
      const item = items[activeIndex];
      if (item) handleSelect(item);
    } else if (e.key === "Escape") {
      e.preventDefault();
      onClose();
    }
  };

  const handleSelect = (item: PaletteItem) => {
    if (item.type === "channel" && onChannelSelect && item.data) {
      onChannelSelect(item.data);
      onClose();
    } else if (item.type === "command") {
      // Commands could navigate - just close for now
      onClose();
    }
  };

  if (!open) return null;

  return (
    <>
      {/* Backdrop */}
      <div className="fixed inset-0 bg-black/40 z-50" onClick={onClose} />

      {/* Palette */}
      <div className="fixed top-[15%] left-1/2 -translate-x-1/2 w-full max-w-lg z-50">
        <div className="bg-white rounded-xl shadow-2xl border border-gray-200 overflow-hidden">
          {/* Search input */}
          <div className="flex items-center gap-3 px-4 py-3 border-b border-gray-100">
            <Search size={18} className="text-gray-400" />
            <input
              ref={inputRef}
              type="text"
              value={query}
              onChange={(e) => {
                setQuery(e.target.value);
                setActiveIndex(0);
              }}
              onKeyDown={handleKeyDown}
              placeholder="Search channels, people, files, commands..."
              className="flex-1 text-sm focus:outline-none bg-transparent"
            />
          </div>

          {/* Results */}
          <div className="max-h-80 overflow-y-auto py-2">
            {items.length === 0 ? (
              <div className="px-4 py-8 text-center text-sm text-gray-400">
                No results found.
              </div>
            ) : (
              <>
                {/* Group label */}
                {query.trim() === "" && (
                  <div className="px-4 py-1 text-xs font-semibold text-gray-400 uppercase">
                    Channels
                  </div>
                )}

                {items.map((item, i) => {
                  const Icon = item.icon;
                  const isActive = i === activeIndex;
                  return (
                    <div key={`${item.type}-${item.id}`}>
                      {item.type === "command" && i > 0 && items[i - 1].type !== "command" && (
                        <div className="px-4 py-1 mt-1 text-xs font-semibold text-gray-400 uppercase">
                          Commands
                        </div>
                      )}
                      <button
                        onClick={() => handleSelect(item)}
                        onMouseEnter={() => setActiveIndex(i)}
                        className={`w-full flex items-center gap-3 px-4 py-2 text-left transition-colors ${
                          isActive ? "bg-slack-purple/10" : "hover:bg-gray-50"
                        }`}
                      >
                        <Icon size={16} className={isActive ? "text-slack-purple" : "text-gray-400"} />
                        <span className={`flex-1 text-sm ${isActive ? "text-slack-purple font-medium" : "text-gray-700"}`}>
                          {item.type === "channel" ? `#${item.label}` : item.label}
                        </span>
                        {isActive && <ArrowRight size={14} className="text-slack-purple" />}
                      </button>
                    </div>
                  );
                })}
              </>
            )}
          </div>

          {/* Footer */}
          <div className="px-4 py-2 border-t border-gray-100 flex items-center gap-4 text-xs text-gray-400">
            <span className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 rounded border border-gray-200 bg-gray-50">↑↓</kbd>
              Navigate
            </span>
            <span className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 rounded border border-gray-200 bg-gray-50">↵</kbd>
              Select
            </span>
            <span className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 rounded border border-gray-200 bg-gray-50">Esc</kbd>
              Close
            </span>
            <span className="ml-auto flex items-center gap-1">
              <Command size={12} />
              Ctrl+K
            </span>
          </div>
        </div>
      </div>
    </>
  );
}