import { useState, useCallback, useEffect, useRef } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Search, X, Loader2, ArrowUp } from 'lucide-react';
import { client } from '@/client/client.gen';
import type { RoomMessageResponse } from '@/client';

interface SearchResult {
  messages: RoomMessageResponse[];
  total: number;
}

interface RoomMessageSearchProps {
  roomId: string;
  onSelectMessage?: (message: RoomMessageResponse) => void;
  onClose: () => void;
}

export function RoomMessageSearch({ roomId, onSelectMessage, onClose }: RoomMessageSearchProps) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult | null>(null);
  const [isSearching, setIsSearching] = useState(false);
  const [offset, setOffset] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  const handleSearch = useCallback(async (searchQuery: string, searchOffset = 0) => {
    if (!searchQuery.trim()) {
      setResults(null);
      return;
    }

    setIsSearching(true);
    try {
      const resp = await client.get({
        url: `/api/rooms/${roomId}/messages/search`,
        params: { q: searchQuery, limit: 20, offset: searchOffset },
      });
      const data = (resp.data as any)?.data as SearchResult | undefined;
      if (data) {
        setResults(data);
        setOffset(searchOffset);
      }
    } catch (err) {
      console.error('Search failed:', err);
    } finally {
      setIsSearching(false);
    }
  }, [roomId]);

  const handleLoadMore = useCallback(() => {
    if (results && results.messages.length < results.total) {
      handleSearch(query, offset + 20);
    }
  }, [query, results, offset, handleSearch]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch(query);
    }
  };

  const highlightText = (text: string, searchQuery: string) => {
    if (!searchQuery.trim()) return text;
    const regex = new RegExp(`(${searchQuery})`, 'gi');
    const parts = text.split(regex);
    return parts.map((part, i) => 
      regex.test(part) ? (
        <mark key={i} className="bg-yellow-200 text-inherit">{part}</mark>
      ) : (
        part
      )
    );
  };

  return (
    <div className="flex h-full flex-col bg-background">
      {/* Header */}
      <div className="flex items-center gap-2 border-b border-border p-3">
        <div className="relative flex-1">
          <Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            ref={inputRef}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Search messages..."
            className="pl-9"
          />
        </div>
        <Button variant="ghost" size="icon" onClick={onClose}>
          <X className="h-4 w-4" />
        </Button>
      </div>

      {/* Results */}
      <ScrollArea className="flex-1">
        {isSearching && (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        )}

        {!isSearching && results && results.messages.length === 0 && (
          <div className="py-8 text-center text-sm text-muted-foreground">
            No messages found
          </div>
        )}

        {!isSearching && results && results.messages.length > 0 && (
          <div className="space-y-2 p-3">
            <div className="mb-2 text-xs text-muted-foreground">
              {results.total} message{results.total !== 1 ? 's' : ''} found
            </div>

            {results.messages.map((message) => (
              <button
                key={message.id}
                onClick={() => onSelectMessage?.(message)}
                className="w-full rounded-lg border border-border/50 bg-muted/20 p-3 text-left hover:bg-muted/40 transition-colors"
              >
                <div className="mb-1 flex items-center justify-between">
                  <span className="text-xs font-medium text-foreground">
                    {message.display_name || 'Unknown'}
                  </span>
                  <span className="text-[10px] text-muted-foreground">
                    {new Date(message.send_at).toLocaleString()}
                  </span>
                </div>
                <div className="text-sm text-foreground break-words line-clamp-2">
                  {highlightText(message.content, query)}
                </div>
              </button>
            ))}

            {results.messages.length < results.total && (
              <Button
                variant="outline"
                className="mt-2 w-full"
                onClick={handleLoadMore}
              >
                <ArrowUp className="mr-2 h-4 w-4" />
                Load more
              </Button>
            )}
          </div>
        )}

        {!isSearching && !results && (
          <div className="py-12 text-center">
            <Search className="mx-auto mb-3 h-12 w-12 text-muted-foreground/50" />
            <p className="text-sm text-muted-foreground">
              Type to search messages
            </p>
          </div>
        )}
      </ScrollArea>
    </div>
  );
}
