import React, { useEffect, useState } from 'react';
import { Sparkles, Loader2, AlertCircle } from 'lucide-react';
import { PlaylistCard } from './PlaylistCard';
import { useToast } from '@/hooks/useToast';
import {
  getPlaylistRecommendations,
  type GetRecommendationsParams,
  type PlaylistRecommendation,
} from '../services/playlistService';
import type { Playlist } from '../types';

interface PlaylistRecommendationsProps {
  limit?: number;
  minScore?: number;
  includeOwn?: boolean;
  onPlaylistClick?: (playlist: Playlist) => void;
  className?: string;
}

/**
 * PlaylistRecommendations - Composant d'affichage des recommandations de playlists
 * T0499: Create Playlist Recommendations Frontend
 */
export const PlaylistRecommendations: React.FC<
  PlaylistRecommendationsProps
> = ({
  limit = 20,
  minScore = 0.1,
  includeOwn = false,
  onPlaylistClick,
  className,
}) => {
  const [recommendations, setRecommendations] = useState<
    PlaylistRecommendation[]
  >([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { error: toastError } = useToast();

  useEffect(() => {
    const fetchRecommendations = async () => {
      setIsLoading(true);
      setError(null);

      try {
        const params: GetRecommendationsParams = {
          limit,
          min_score: minScore,
          include_own: includeOwn,
        };

        const response = await getPlaylistRecommendations(params);
        setRecommendations(response.recommendations);
      } catch (err) {
        const errorMessage =
          err instanceof Error
            ? err.message
            : 'Erreur lors du chargement des recommandations';
        setError(errorMessage);
        toastError(errorMessage);
      } finally {
        setIsLoading(false);
      }
    };

    fetchRecommendations();
  }, [limit, minScore, includeOwn]);

  if (isLoading) {
    return (
      <div
        className={`flex items-center justify-center py-12 ${className}`}
        role="region"
        aria-live="polite"
      >
        <Loader2
          className="h-8 w-8 animate-spin text-muted-foreground"
          aria-hidden="true"
        />
        <span className="ml-3 text-muted-foreground">
          Chargement des recommandations...
        </span>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`text-center py-12 ${className}`} role="alert">
        <AlertCircle
          className="h-12 w-12 text-destructive mx-auto mb-4"
          aria-hidden="true"
        />
        <p className="text-destructive">{error}</p>
      </div>
    );
  }

  if (recommendations.length === 0) {
    return (
      <div
        className={`text-center py-12 ${className}`}
        role="region"
        aria-live="polite"
      >
        <Sparkles
          className="h-12 w-12 text-muted-foreground mx-auto mb-4"
          aria-hidden="true"
        />
        <p className="text-muted-foreground">
          Aucune recommandation disponible pour le moment
        </p>
      </div>
    );
  }

  return (
    <div
      className={className}
      role="region"
      aria-label="Playlists recommandées"
    >
      {/* En-tête */}
      <div className="mb-6">
        <div className="flex items-center gap-2 mb-2">
          <Sparkles className="h-5 w-5 text-primary" aria-hidden="true" />
          <h2 className="text-2xl font-bold">Recommandations pour vous</h2>
        </div>
        <p className="text-sm text-muted-foreground" aria-live="polite">
          {recommendations.length} playlist
          {recommendations.length > 1 ? 's' : ''} recommandée
          {recommendations.length > 1 ? 's' : ''}
        </p>
      </div>

      {/* Liste des playlists recommandées */}
      <div
        className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
        role="list"
        aria-label="Liste des playlists recommandées"
      >
        {recommendations.map((rec) => (
          <div key={rec.playlist.id} className="relative" role="listitem">
            <PlaylistCard
              playlist={rec.playlist}
              onClick={() => onPlaylistClick?.(rec.playlist)}
            />
            {/* Badge de score et raison */}
            <div
              className="absolute top-2 right-2 bg-background/80 backdrop-blur-sm rounded-md px-2 py-1 text-xs"
              aria-label={`Score de recommandation: ${(rec.score * 100).toFixed(0)}%`}
            >
              <div className="flex items-center gap-1">
                <Sparkles className="h-3 w-3 text-primary" aria-hidden="true" />
                <span className="font-medium">
                  {(rec.score * 100).toFixed(0)}%
                </span>
              </div>
              {rec.reason && (
                <p
                  className="text-muted-foreground text-[10px] mt-1 max-w-[120px] truncate"
                  title={rec.reason}
                  aria-label={`Raison: ${rec.reason}`}
                >
                  {rec.reason}
                </p>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
