"use client";

import { forwardRef, useImperativeHandle, useState } from "react";
import { cn } from "@/lib/utils";
import type { SlashCommandItem } from "./slash-commands";

interface SlashCommandListProps {
  items: SlashCommandItem[];
  command: (item: SlashCommandItem) => void;
}

export interface SlashCommandListHandle {
  onKeyDown: (props: { event: KeyboardEvent }) => boolean;
}

// Keyed by the filtered set below so the selection resets to the top
// whenever the query narrows or widens the list, without reaching for
// an effect or a ref write during render to detect that change.
const SlashCommandListInner = forwardRef<SlashCommandListHandle, SlashCommandListProps>(
  ({ items, command }, ref) => {
    const [selectedIndex, setSelectedIndex] = useState(0);

    useImperativeHandle(ref, () => ({
      onKeyDown: ({ event }) => {
        if (event.key === "ArrowDown") {
          setSelectedIndex((prev) => (prev + 1) % items.length);
          return true;
        }
        if (event.key === "ArrowUp") {
          setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
          return true;
        }
        if (event.key === "Enter") {
          if (items[selectedIndex]) command(items[selectedIndex]);
          return true;
        }
        return false;
      },
    }));

    if (items.length === 0) {
      return (
        <div className="w-64 rounded-xl border border-border bg-popover p-3 text-sm text-muted-foreground shadow-lg">
          No results
        </div>
      );
    }

    return (
      <div className="w-64 max-h-80 overflow-y-auto rounded-xl border border-border bg-popover p-1.5 shadow-lg">
        {items.map((item, index) => (
          <button
            key={item.title}
            type="button"
            onClick={() => command(item)}
            onMouseEnter={() => setSelectedIndex(index)}
            className={cn(
              "flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition-colors",
              index === selectedIndex
                ? "bg-accent text-accent-foreground"
                : "text-foreground hover:bg-accent/60",
            )}
          >
            <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-background text-muted-foreground">
              <item.icon className="h-4 w-4" />
            </span>
            <span className="min-w-0">
              <span className="block truncate text-[13px] font-medium">{item.title}</span>
              <span className="block truncate text-[11px] text-muted-foreground">
                {item.description}
              </span>
            </span>
          </button>
        ))}
      </div>
    );
  },
);

SlashCommandListInner.displayName = "SlashCommandListInner";

export const SlashCommandList = forwardRef<SlashCommandListHandle, SlashCommandListProps>(
  (props, ref) => {
    const signature = props.items.map((item) => item.title).join("|");
    return <SlashCommandListInner key={signature} ref={ref} {...props} />;
  },
);

SlashCommandList.displayName = "SlashCommandList";
