'use client';

import { forwardRef, useImperativeHandle, useState, useCallback, useEffect, type KeyboardEvent } from 'react';
import type { MentionItem } from './types';

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

interface MentionListProps {
  items: MentionItem[];
  command: (item: MentionItem) => void;
}

export const MentionList = forwardRef<MentionListRef, MentionListProps>(
  ({ items, command }, ref) => {
    const [selectedIndex, setSelectedIndex] = useState(0);

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

    const select = useCallback(
      (index: number) => {
        const item = items[index];
        if (item) command(item);
      },
      [items, command],
    );

    useImperativeHandle(ref, () => ({
      onKeyDown: (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') {
          select(selectedIndex);
          return true;
        }
        return false;
      },
    }));

    if (items.length === 0) return null;

    return (
      <div className="markdown-mention-list">
        {items.map((item, i) => {
          const isSelected = i === selectedIndex;
          const cls = `markdown-mention-item ${isSelected ? 'selected' : ''}`;
          return (
            <button key={item.id} type="button" className={cls} onClick={() => select(i)}>
              {item.thumbnail && (
                <img src={item.thumbnail} alt="" className="markdown-mention-avatar" />
              )}
              <div className="markdown-mention-info">
                <span className="markdown-mention-name">{item.label}</span>
                {item.description && (
                  <span className="markdown-mention-desc">{item.description}</span>
                )}
              </div>
            </button>
          );
        })}
      </div>
    );
  },
);

MentionList.displayName = 'MentionList';
