/**
 * Mention suggestion dropdown with keyboard navigation.
 * Supports user, channel, ai, and command mention types.
 */

import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Hash, Bot, Command, User } from 'lucide-react';
import type { MentionItem, MentionType } from './types';
import { cn } from '@/lib/utils';

interface SuggestionListProps {
  items: MentionItem[];
  command: (item: { id: string; label: string; type: MentionType }) => void;
}

export const SuggestionList = forwardRef<{ onKeyDown: (props: { event: KeyboardEvent }) => boolean }, SuggestionListProps>(
  ({ items, command }, ref) => {
    const [selectedIndex, setSelectedIndex] = useState(0);

    const selectItem = (index: number) => {
      const item = items[index];
      if (item) command({ id: item.id, label: item.label, type: item.type });
    };

    useImperativeHandle(ref, () => ({
      onKeyDown: ({ event }: { event: KeyboardEvent }) => {
        if (event.key === 'ArrowUp') {
          setSelectedIndex((i) => (i + items.length - 1) % items.length);
          return true;
        }
        if (event.key === 'ArrowDown') {
          setSelectedIndex((i) => (i + 1) % items.length);
          return true;
        }
        if (event.key === 'Enter') {
          selectItem(selectedIndex);
          return true;
        }
        if (event.key === 'Escape') {
          return true;
        }
        return false;
      },
    }));

    useEffect(() => setSelectedIndex(0), [items]);

    const getIcon = (type: MentionType) => {
      switch (type) {
        case 'channel': return <Hash size={14} className="text-gray-500" />;
        case 'ai': return <Bot size={14} className="text-purple-500" />;
        case 'command': return <Command size={14} className="text-orange-500" />;
        default: return <User size={14} className="text-blue-500" />;
      }
    };

    const getBadge = (type: MentionType) => {
      if (type === 'ai') return <span className="ml-auto text-[10px] bg-purple-100 text-purple-700 px-1.5 rounded">AI</span>;
      if (type === 'command') return <span className="ml-auto text-[10px] bg-orange-100 text-orange-700 px-1.5 rounded">Cmd</span>;
      if (type === 'channel') return <span className="ml-auto text-[10px] bg-gray-100 text-gray-500 px-1.5 rounded">#</span>;
      return null;
    };

    if (items.length === 0) {
      return (
        <div className="bg-card border border-border rounded-lg shadow-xl overflow-hidden min-w-[200px] py-1">
          <div className="px-4 py-3 text-sm text-muted-foreground text-center">No results</div>
        </div>
      );
    }

    return (
      <div className="bg-card border border-border rounded-lg shadow-xl overflow-hidden min-w-[200px] max-h-[280px] overflow-y-auto py-1 z-50">
        {items.map((item, index) => (
          <button
            key={item.id}
            className={cn(
              'w-full flex items-center gap-2.5 px-3 py-2 text-sm transition-colors text-left',
              index === selectedIndex ? 'bg-accent' : 'hover:bg-muted/60',
            )}
            onClick={() => selectItem(index)}
          >
            {item.avatar ? (
              <Avatar className="h-5 w-5 shrink-0">
                <AvatarImage src={item.avatar} alt={item.label} />
                <AvatarFallback className="text-[10px]">
                  {item.label.charAt(0).toUpperCase()}
                </AvatarFallback>
              </Avatar>
            ) : (
              <span className="shrink-0">{getIcon(item.type)}</span>
            )}
            <span className="truncate font-medium text-foreground">{item.label}</span>
            {getBadge(item.type)}
          </button>
        ))}
      </div>
    );
  },
);

SuggestionList.displayName = 'SuggestionList';
