import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Hash, Lock, MessageSquare, X } from 'lucide-react';
import { convertEmojiShortcodes } from '@/utils/emojiUtils';

interface SearchResult {
  id: number;
  msg: string;
  ts: string;
  u: {
    username: string;
    name?: string;
  };
  room_id: number;
  room_name: string;
  room_fname: string;
  room_type: string;
}

interface SearchResultsProps {
  results: SearchResult[];
  query: string;
  onClose: () => void;
  onRoomSelect: (roomId: string) => void;
}

export function SearchResults({ results, query, onClose, onRoomSelect }: SearchResultsProps) {
  const getRoomIcon = (roomType: string) => {
    switch (roomType) {
      case 'c':
        return <Hash className="h-3 w-3 text-blue-500" />;
      case 'p':
        return <Lock className="h-3 w-3 text-orange-500" />;
      case 'd':
        return <MessageSquare className="h-3 w-3 text-green-500" />;
      default:
        return <Hash className="h-3 w-3 text-gray-500" />;
    }
  };

  const highlightText = (text: string, query: string) => {
    if (!query) return convertEmojiShortcodes(text);
    
    // First convert emoji shortcodes
    const textWithEmoji = convertEmojiShortcodes(text);
    
    const regex = new RegExp(`(${query})`, 'gi');
    const parts = textWithEmoji.split(regex);
    
    return parts.map((part, index) => 
      regex.test(part) ? (
        <span key={index} className="bg-yellow-200 font-medium">
          {part}
        </span>
      ) : (
        part
      )
    );
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  };

  return (
    <Card className="absolute top-full left-0 right-0 z-10 mt-2 max-h-96 overflow-y-auto">
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm">
          Search Results for "{query}" ({results.length})
        </CardTitle>
        <Button variant="ghost" size="sm" onClick={onClose}>
          <X className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent className="pt-0">
        {results.length === 0 ? (
          <p className="text-sm text-muted-foreground">No messages found matching your search.</p>
        ) : (
          <div className="space-y-3">
            {results.map((result) => (
              <div 
                key={result.id}
                className="border rounded-lg p-3 hover:bg-gray-50 cursor-pointer"
                onClick={() => {
                  onRoomSelect(result.room_id.toString());
                  onClose();
                }}
              >
                <div className="flex items-center gap-2 mb-2">
                  {getRoomIcon(result.room_type)}
                  <span className="text-sm font-medium">
                    {result.room_fname || result.room_name || 'Unnamed Room'}
                  </span>
                  <Badge variant="outline" className="text-xs">
                    {result.u.name || result.u.username}
                  </Badge>
                  <span className="text-xs text-muted-foreground ml-auto">
                    {formatTime(result.ts)}
                  </span>
                </div>
                <div className="text-sm">
                  {highlightText(result.msg, query)}
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 