import React, { useState, useEffect } from 'react';
import { Search, Filter, X, Loader2 } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { PlaylistCard } from './PlaylistCard';
import { useToast } from '@/hooks/useToast';
import {
  playlistsApi,
  type SearchPlaylistsParams,
} from '@/services/api/playlists';
import type { Playlist } from '../types';
import { useDebounce } from '@/hooks/useDebounce';

interface PlaylistSearchProps {
  onPlaylistClick?: (playlist: Playlist) => void;
  className?: string;
}

/**
 * PlaylistSearch - Composant de recherche de playlists
 */
export const PlaylistSearch: React.FC<PlaylistSearchProps> = ({
  onPlaylistClick,
  className,
}) => {
  const [query, setQuery] = useState('');
  const [playlists, setPlaylists] = useState<Playlist[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errorState, setErrorState] = useState<string | null>(null);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState<{
    user_id?: string;
    is_public?: boolean;
  }>({});
  const { error: toastError } = useToast();

  // Debounce de la recherche pour éviter trop de requêtes
  const debouncedQuery = useDebounce(query, 500);

  // Effectuer la recherche quand la query change
  useEffect(() => {
    const performSearch = async () => {
      if (
        !debouncedQuery.trim() &&
        !filters.user_id &&
        filters.is_public === undefined
      ) {
        setPlaylists([]);
        setTotal(0);
        return;
      }

      setIsLoading(true);
      setErrorState(null);

      try {
        const params: SearchPlaylistsParams = {
          q: debouncedQuery.trim() || undefined,
          page,
          limit,
          ...filters,
        };

        const response = await playlistsApi.search(params);
        setPlaylists(response.playlists);
        setTotal(response.total);
      } catch (err) {
        const errorMessage =
          err instanceof Error ? err.message : 'Erreur lors de la recherche';
        setErrorState(errorMessage);
        toastError(errorMessage);
      } finally {
        setIsLoading(false);
      }
    };

    performSearch();
  }, [
    debouncedQuery,
    page,
    limit,
    filters.user_id,
    filters.is_public,
    toastError,
  ]);

  // Réinitialiser la page quand la query ou les filtres changent
  useEffect(() => {
    setPage(1);
  }, [debouncedQuery, filters.user_id, filters.is_public]);

  const handleFilterChange = (
    key: 'user_id' | 'is_public',
    value: string | boolean | undefined,
  ) => {
    setFilters((prev) => {
      const newFilters = { ...prev };
      if (value === undefined) {
        delete newFilters[key];
      } else {
        // Safe cast as we control the input types
        if (key === 'user_id' && typeof value === 'string') {
          newFilters.user_id = value;
        } else if (key === 'is_public' && typeof value === 'boolean') {
          newFilters.is_public = value;
        }
      }
      return newFilters;
    });
  };

  const clearFilters = () => {
    setFilters({});
    setQuery('');
  };

  const hasActiveFilters =
    filters.user_id !== undefined ||
    filters.is_public !== undefined ||
    query.trim() !== '';

  const totalPages = Math.ceil(total / limit);

  return (
    <div
      className={className}
      role="search"
      aria-label="Recherche de playlists"
    >
      {/* Barre de recherche */}
      <div className="mb-6">
        <div className="flex gap-2 mb-4">
          <div className="flex-1 relative">
            <Search
              className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"
              aria-hidden="true"
            />
            <Input
              type="text"
              placeholder="Rechercher des playlists..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              className="pl-10"
              aria-label="Rechercher des playlists"
              // aria-invalid={errorState ? 'true' : 'false'}
            />
          </div>
          <Button
            variant="outline"
            size="icon"
            onClick={() => setShowFilters(!showFilters)}
            className={showFilters ? 'bg-accent' : ''}
            aria-label={
              showFilters ? 'Masquer les filtres' : 'Afficher les filtres'
            }
            aria-expanded={showFilters}
          >
            <Filter className="h-4 w-4" aria-hidden="true" />
          </Button>
          {hasActiveFilters && (
            <Button
              variant="outline"
              size="icon"
              onClick={clearFilters}
              aria-label="Effacer les filtres et la recherche"
            >
              <X className="h-4 w-4" aria-hidden="true" />
            </Button>
          )}
        </div>

        {/* Filtres */}
        {showFilters && (
          <div
            className="border rounded-lg p-4 space-y-4 bg-card"
            role="region"
            aria-label="Filtres de recherche de playlists"
          >
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Filtre User ID */}
              <div>
                <label
                  htmlFor="filter-user-id"
                  className="text-sm font-medium mb-2 block"
                >
                  ID Utilisateur
                </label>
                <Input
                  id="filter-user-id"
                  type="number"
                  placeholder="Filtrer par utilisateur"
                  value={filters.user_id || ''}
                  onChange={(e) => {
                    const value = e.target.value || undefined;
                    handleFilterChange('user_id', value);
                  }}
                  aria-label="Filtrer par ID utilisateur"
                />
              </div>

              {/* Filtre Is Public */}
              <div>
                <label
                  htmlFor="filter-is-public"
                  className="text-sm font-medium mb-2 block"
                >
                  Statut
                </label>
                <select
                  id="filter-is-public"
                  className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                  value={
                    filters.is_public === undefined
                      ? ''
                      : filters.is_public.toString()
                  }
                  onChange={(e) => {
                    const value =
                      e.target.value === ''
                        ? undefined
                        : e.target.value === 'true';
                    handleFilterChange('is_public', value);
                  }}
                  aria-label="Filtrer par visibilité de la playlist"
                >
                  <option value="">Tous</option>
                  <option value="true">Publiques</option>
                  <option value="false">Privées</option>
                </select>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Résultats */}
      <div role="region" aria-live="polite" aria-atomic="true">
        {isLoading && (
          <div className="flex items-center justify-center py-12">
            <Loader2
              className="h-8 w-8 animate-spin text-muted-foreground"
              aria-hidden="true"
            />
            <span className="ml-3 text-muted-foreground">
              Recherche en cours...
            </span>
          </div>
        )}

        {errorState && !isLoading && (
          <div className="text-center py-12 text-destructive" role="alert">
            <p>{errorState}</p>
          </div>
        )}

        {!isLoading && !errorState && (
          <>
            {/* Compteur de résultats */}
            {hasActiveFilters && (
              <div
                className="mb-4 text-sm text-muted-foreground"
                aria-live="polite"
              >
                {total} résultat{total !== 1 ? 's' : ''} trouvé
                {total !== 1 ? 's' : ''}
              </div>
            )}

            {/* Liste des playlists */}
            {playlists.length > 0 ? (
              <div
                className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
                role="list"
                aria-label="Résultats de la recherche de playlists"
              >
                {playlists.map((playlist) => (
                  <PlaylistCard
                    key={playlist.id}
                    playlist={playlist}
                    onClick={() => onPlaylistClick?.(playlist)}
                  />
                ))}
              </div>
            ) : hasActiveFilters ? (
              <div className="text-center py-12 text-muted-foreground">
                <p>Aucune playlist trouvée</p>
              </div>
            ) : null}

            {/* Pagination */}
            {totalPages > 1 && (
              <div
                className="flex items-center justify-center gap-2 mt-6"
                role="navigation"
                aria-label="Pagination des résultats de recherche de playlists"
              >
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={page === 1 || isLoading}
                  aria-label="Page précédente"
                >
                  Précédent
                </Button>
                <span
                  className="text-sm text-muted-foreground"
                  aria-live="polite"
                >
                  Page {page} sur {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                  disabled={page === totalPages || isLoading}
                  aria-label="Page suivante"
                >
                  Suivant
                </Button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};
