/**
 * MessageSearch Component
 * Search within conversation messages with filters
 */

import React, { useState, useCallback, useEffect, useMemo } from 'react';
import {
  Search,
  X,
  ChevronUp,
  ChevronDown,
  Filter,
  User,
  Bot,
  Calendar,
  Hash,
} from 'lucide-react';

interface Message {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: string;
}

interface SearchResult {
  messageId: string;
  matchIndex: number;
  snippet: string;
  role: 'user' | 'assistant' | 'system';
  timestamp: string;
}

interface MessageSearchProps {
  messages: Message[];
  onResultSelect?: (messageId: string) => void;
  onSearchChange?: (query: string) => void;
  onClose?: () => void;
  isOpen?: boolean;
  compact?: boolean;
}

type RoleFilter = 'all' | 'user' | 'assistant';

const MessageSearch: React.FC<MessageSearchProps> = ({
  messages,
  onResultSelect,
  onSearchChange,
  onClose,
  isOpen = true,
  compact = false,
}) => {
  const [query, setQuery] = useState('');
  const [currentIndex, setCurrentIndex] = useState(0);
  const [roleFilter, setRoleFilter] = useState<RoleFilter>('all');
  const [showFilters, setShowFilters] = useState(false);
  const [dateFilter, setDateFilter] = useState<'all' | 'today' | 'week' | 'month'>('all');

  // Filter messages by role and date
  const filteredMessages = useMemo(() => {
    let result = messages;

    // Role filter
    if (roleFilter !== 'all') {
      result = result.filter((msg) => msg.role === roleFilter);
    }

    // Date filter
    if (dateFilter !== 'all') {
      const now = new Date();
      const cutoff = new Date();

      switch (dateFilter) {
        case 'today':
          cutoff.setHours(0, 0, 0, 0);
          break;
        case 'week':
          cutoff.setDate(now.getDate() - 7);
          break;
        case 'month':
          cutoff.setMonth(now.getMonth() - 1);
          break;
      }

      result = result.filter((msg) => new Date(msg.timestamp) >= cutoff);
    }

    return result;
  }, [messages, roleFilter, dateFilter]);

  // Search results
  const results: SearchResult[] = useMemo(() => {
    if (!query.trim()) return [];

    const searchResults: SearchResult[] = [];
    const searchTerm = query.toLowerCase();

    filteredMessages.forEach((message) => {
      const content = message.content.toLowerCase();
      let index = content.indexOf(searchTerm);
      let matchIndex = 0;

      while (index !== -1) {
        // Create snippet with context
        const start = Math.max(0, index - 30);
        const end = Math.min(message.content.length, index + query.length + 30);
        let snippet = message.content.substring(start, end);

        if (start > 0) snippet = '...' + snippet;
        if (end < message.content.length) snippet = snippet + '...';

        searchResults.push({
          messageId: message.id,
          matchIndex,
          snippet,
          role: message.role,
          timestamp: message.timestamp,
        });

        matchIndex++;
        index = content.indexOf(searchTerm, index + 1);
      }
    });

    return searchResults;
  }, [query, filteredMessages]);

  // Update parent when query changes
  useEffect(() => {
    onSearchChange?.(query);
  }, [query, onSearchChange]);

  // Navigate to current result
  useEffect(() => {
    if (results.length > 0 && currentIndex < results.length) {
      onResultSelect?.(results[currentIndex].messageId);
    }
  }, [currentIndex, results, onResultSelect]);

  // Reset current index when results change
  useEffect(() => {
    setCurrentIndex(0);
  }, [results.length]);

  const handlePrevious = useCallback(() => {
    setCurrentIndex((prev) => (prev > 0 ? prev - 1 : results.length - 1));
  }, [results.length]);

  const handleNext = useCallback(() => {
    setCurrentIndex((prev) => (prev < results.length - 1 ? prev + 1 : 0));
  }, [results.length]);

  const handleClear = useCallback(() => {
    setQuery('');
    setCurrentIndex(0);
    onSearchChange?.('');
  }, [onSearchChange]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        if (e.shiftKey) {
          handlePrevious();
        } else {
          handleNext();
        }
      } else if (e.key === 'Escape') {
        onClose?.();
      }
    },
    [handleNext, handlePrevious, onClose]
  );

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

  if (!isOpen) return null;

  return (
    <div className={`bg-gray-800 border-b border-gray-700 ${compact ? 'px-2 py-1.5' : 'px-4 py-2'}`}>
      {/* Search Bar */}
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Search messages..."
            autoFocus
            className="w-full pl-9 pr-8 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500"
          />
          {query && (
            <button
              onClick={handleClear}
              className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-500 hover:text-gray-300"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>

        {/* Results Count & Navigation */}
        {query && (
          <div className="flex items-center gap-1">
            <span className="text-sm text-gray-400 whitespace-nowrap">
              {results.length > 0 ? `${currentIndex + 1}/${results.length}` : '0 results'}
            </span>
            <button
              onClick={handlePrevious}
              disabled={results.length === 0}
              className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded disabled:opacity-50 disabled:cursor-not-allowed"
              title="Previous (Shift+Enter)"
            >
              <ChevronUp className="w-4 h-4" />
            </button>
            <button
              onClick={handleNext}
              disabled={results.length === 0}
              className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded disabled:opacity-50 disabled:cursor-not-allowed"
              title="Next (Enter)"
            >
              <ChevronDown className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Filter Toggle */}
        <button
          onClick={() => setShowFilters(!showFilters)}
          className={`p-2 rounded-lg transition-colors ${
            showFilters ? 'bg-blue-600 text-white' : 'text-gray-400 hover:text-white hover:bg-gray-700'
          }`}
          title="Filters"
        >
          <Filter className="w-4 h-4" />
        </button>

        {/* Close Button */}
        {onClose && (
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg"
            title="Close (Esc)"
          >
            <X className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <div className="flex items-center gap-4 mt-2 pt-2 border-t border-gray-700">
          {/* Role Filter */}
          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-500">From:</span>
            <div className="flex items-center gap-1">
              <button
                onClick={() => setRoleFilter('all')}
                className={`px-2 py-1 text-xs rounded ${
                  roleFilter === 'all'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                }`}
              >
                All
              </button>
              <button
                onClick={() => setRoleFilter('user')}
                className={`flex items-center gap-1 px-2 py-1 text-xs rounded ${
                  roleFilter === 'user'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                }`}
              >
                <User className="w-3 h-3" />
                You
              </button>
              <button
                onClick={() => setRoleFilter('assistant')}
                className={`flex items-center gap-1 px-2 py-1 text-xs rounded ${
                  roleFilter === 'assistant'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                }`}
              >
                <Bot className="w-3 h-3" />
                AI
              </button>
            </div>
          </div>

          {/* Date Filter */}
          <div className="flex items-center gap-2">
            <Calendar className="w-3 h-3 text-gray-500" />
            <select
              value={dateFilter}
              onChange={(e) => setDateFilter(e.target.value as typeof dateFilter)}
              className="px-2 py-1 bg-gray-700 border border-gray-600 rounded text-xs text-white focus:outline-none"
            >
              <option value="all">All time</option>
              <option value="today">Today</option>
              <option value="week">Past week</option>
              <option value="month">Past month</option>
            </select>
          </div>

          {/* Results Stats */}
          <div className="flex items-center gap-1 text-xs text-gray-500">
            <Hash className="w-3 h-3" />
            <span>Searching {filteredMessages.length} messages</span>
          </div>
        </div>
      )}

      {/* Quick Results Preview (when query exists) */}
      {query && results.length > 0 && !compact && (
        <div className="mt-2 max-h-40 overflow-y-auto space-y-1">
          {results.slice(0, 5).map((result, index) => (
            <button
              key={`${result.messageId}-${result.matchIndex}`}
              onClick={() => {
                setCurrentIndex(index);
                onResultSelect?.(result.messageId);
              }}
              className={`w-full flex items-start gap-2 p-2 rounded text-left transition-colors ${
                index === currentIndex
                  ? 'bg-blue-600/20 border border-blue-500/30'
                  : 'hover:bg-gray-700'
              }`}
            >
              <div
                className={`mt-0.5 p-1 rounded ${
                  result.role === 'user' ? 'bg-green-500/20' : 'bg-blue-500/20'
                }`}
              >
                {result.role === 'user' ? (
                  <User className="w-3 h-3 text-green-400" />
                ) : (
                  <Bot className="w-3 h-3 text-blue-400" />
                )}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm text-gray-300 truncate">{result.snippet}</p>
                <p className="text-xs text-gray-500">{formatTime(result.timestamp)}</p>
              </div>
            </button>
          ))}
          {results.length > 5 && (
            <p className="text-xs text-gray-500 text-center py-1">
              +{results.length - 5} more results
            </p>
          )}
        </div>
      )}
    </div>
  );
};

export default MessageSearch;
