import { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, type SearchResult } from './Search';
import { searchTracks } from '@/features/tracks/services/trackListService';
import { playlistsApi } from '@/services/api/playlists';
import { searchUsers } from '@/features/search/services/searchService';
import { useTranslation } from '@/hooks/useTranslation';
import { logger } from '@/utils/logger';

/**
 * FE-COMP-008: Global search bar component with autocomplete
 * Can be used in the header or anywhere in the app
 */

export interface GlobalSearchBarProps {
  className?: string;
  placeholder?: string;
  onSearch?: (query: string) => void;
}

/**
 * Global search bar with autocomplete suggestions for tracks, playlists, and users
 */
export function GlobalSearchBar({
  className,
  placeholder,
  onSearch,
}: GlobalSearchBarProps) {
  const navigate = useNavigate();
  const { t } = useTranslation();

  // Fetch autocomplete suggestions
  const fetchSuggestions = useCallback(
    async (query: string): Promise<SearchResult[]> => {
      if (!query.trim()) {
        return [];
      }

      try {
        // Fetch suggestions from all sources in parallel
        const [tracksData, playlistsData, usersData] = await Promise.allSettled(
          [
            searchTracks(query, { pagination: { page: 1, limit: 3 } }),
            playlistsApi.search({ q: query, page: 1, limit: 3 }),
            searchUsers({ query, page: 1, limit: 3 }),
          ],
        );

        const results: SearchResult[] = [];

        // Add track suggestions
        if (tracksData.status === 'fulfilled' && tracksData.value?.data) {
          tracksData.value.data.forEach((track: any) => {
            results.push({
              id: track.id,
              type: 'track',
              title: track.title,
              subtitle: track.artist ? `by ${track.artist}` : undefined,
              image: track.cover_url,
            });
          });
        }

        // Add playlist suggestions
        if (
          playlistsData.status === 'fulfilled' &&
          playlistsData.value?.playlists
        ) {
          playlistsData.value.playlists.forEach((playlist: any) => {
            results.push({
              id: playlist.id,
              type: 'playlist',
              title: playlist.title,
              subtitle: playlist.is_public ? 'Public' : 'Private',
              image: playlist.cover_url,
            });
          });
        }

        // Add user suggestions
        if (usersData.status === 'fulfilled' && usersData.value?.users) {
          usersData.value.users.forEach((user: any) => {
            results.push({
              id: user.id,
              type: 'user',
              title: user.username,
              subtitle: user.email,
              image: user.avatar_url,
            });
          });
        }

        return results.slice(0, 8); // Limit to 8 total suggestions
      } catch (error) {
        logger.error('Error fetching search suggestions', {
          error: error instanceof Error ? error.message : String(error),
          stack: error instanceof Error ? error.stack : undefined,
        });
        return [];
      }
    },
    [],
  );

  // Handle search action
  const handleSearch = useCallback(
    (query: string) => {
      if (query.trim()) {
        navigate(`/search?q=${encodeURIComponent(query)}`);
        onSearch?.(query);
      }
    },
    [navigate, onSearch],
  );

  // Handle result selection
  const handleResultSelect = useCallback(
    (result: SearchResult) => {
      switch (result.type) {
        case 'track':
          navigate(`/tracks/${result.id}`);
          break;
        case 'playlist':
          navigate(`/playlists/${result.id}`);
          break;
        case 'user':
          navigate(`/users/${result.id}`);
          break;
      }
    },
    [navigate],
  );

  return (
    <Search
      onSearch={handleSearch}
      onResultSelect={handleResultSelect}
      fetchSuggestions={fetchSuggestions}
      placeholder={
        placeholder ||
        t('common.search') ||
        'Search tracks, playlists, users...'
      }
      showSuggestions={true}
      showHistory={true}
      className={className}
      // CRITIQUE FIX #21: Augmenter le délai de debouncing à 500ms pour réduire les requêtes API
      // Un délai de 500ms est optimal pour équilibrer réactivité et performance
      debounceDelay={500}
    />
  );
}
