/**
 * Composant pour afficher les analytics d'une playlist
 * T0492: Create Playlist Analytics Frontend
 */

import { useState, useEffect } from 'react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Play, Share2, Heart, Eye, TrendingUp } from 'lucide-react';
import { cn } from '@/lib/utils';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';

/**
 * Interface pour les données d'analytics d'une playlist
 */
export interface PlaylistAnalyticsData {
  playlist_id: string;
  play_count: number;
  share_count: number;
  like_count: number;
  view_count: number;
  unique_listeners?: number;
  average_completion_rate?: number;
  created_at: string;
  updated_at: string;
}

interface PlaylistAnalyticsProps {
  // FE-TYPE-001: IDs are strings (UUIDs), not numbers
  playlistId: string;
  className?: string;
}

/**
 * Composant PlaylistAnalytics
 * Affiche les statistiques d'une playlist (plays, shares, likes, views)
 */
export function PlaylistAnalytics({
  playlistId,
  className,
}: PlaylistAnalyticsProps) {
  const [analytics, setAnalytics] = useState<PlaylistAnalyticsData | null>(
    null,
  );
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadAnalytics();
  }, [playlistId]);

  const loadAnalytics = async () => {
    setLoading(true);
    setError(null);

    try {
      // TODO: T0491 - Remplacer par l'appel API réel une fois le backend implémenté
      // const data = await getPlaylistAnalytics(playlistId);

      // Pour l'instant, on simule des données vides
      // Une fois T0491 complété, on pourra appeler l'endpoint réel
      const mockData: PlaylistAnalyticsData = {
        playlist_id: playlistId,
        play_count: 0,
        share_count: 0,
        like_count: 0,
        view_count: 0,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };

      setAnalytics(mockData);
    } catch (err: unknown) {
      const apiError = parseApiError(err);
      logger.error('Failed to load playlist analytics:', {
        message: apiError.message,
      });
      setError(apiError.message);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Card className={cn(className)}>
        <CardHeader>
          <CardTitle>Statistiques de la playlist</CardTitle>
          <CardDescription>
            Analytics et métriques de performance
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[200px]">
            <div className="text-muted-foreground">Chargement...</div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className={cn(className)}>
        <CardHeader>
          <CardTitle>Statistiques de la playlist</CardTitle>
          <CardDescription>
            Analytics et métriques de performance
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[200px] text-destructive">
            {error}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!analytics) {
    return (
      <Card className={cn(className)}>
        <CardHeader>
          <CardTitle>Statistiques de la playlist</CardTitle>
          <CardDescription>
            Analytics et métriques de performance
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[200px] text-muted-foreground">
            Aucune donnée disponible
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className={cn('space-y-4', className)}>
      {/* Statistiques principales */}
      <Card>
        <CardHeader>
          <CardTitle>Statistiques de la playlist</CardTitle>
          <CardDescription>
            Vue d'ensemble des métriques de performance
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Play Count */}
            <div className="flex flex-col p-4 rounded-lg border bg-card">
              <div className="flex items-center gap-2 mb-2">
                <Play className="w-5 h-5 text-primary" />
                <span className="text-sm text-muted-foreground">Lectures</span>
              </div>
              <span className="text-3xl font-bold">
                {analytics.play_count.toLocaleString()}
              </span>
              <span className="text-xs text-muted-foreground mt-1">
                Nombre total de lectures
              </span>
            </div>

            {/* Share Count */}
            <div className="flex flex-col p-4 rounded-lg border bg-card">
              <div className="flex items-center gap-2 mb-2">
                <Share2 className="w-5 h-5 text-primary" />
                <span className="text-sm text-muted-foreground">Partages</span>
              </div>
              <span className="text-3xl font-bold">
                {analytics.share_count.toLocaleString()}
              </span>
              <span className="text-xs text-muted-foreground mt-1">
                Nombre de partages
              </span>
            </div>

            {/* Like Count */}
            <div className="flex flex-col p-4 rounded-lg border bg-card">
              <div className="flex items-center gap-2 mb-2">
                <Heart className="w-5 h-5 text-primary" />
                <span className="text-sm text-muted-foreground">J'aime</span>
              </div>
              <span className="text-3xl font-bold">
                {analytics.like_count.toLocaleString()}
              </span>
              <span className="text-xs text-muted-foreground mt-1">
                Nombre de likes
              </span>
            </div>

            {/* View Count */}
            <div className="flex flex-col p-4 rounded-lg border bg-card">
              <div className="flex items-center gap-2 mb-2">
                <Eye className="w-5 h-5 text-primary" />
                <span className="text-sm text-muted-foreground">Vues</span>
              </div>
              <span className="text-3xl font-bold">
                {analytics.view_count.toLocaleString()}
              </span>
              <span className="text-xs text-muted-foreground mt-1">
                Nombre de vues
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Statistiques supplémentaires */}
      {(analytics.unique_listeners !== undefined ||
        analytics.average_completion_rate !== undefined) && (
        <Card>
          <CardHeader>
            <CardTitle>Métriques avancées</CardTitle>
            <CardDescription>
              Statistiques détaillées de performance
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {analytics.unique_listeners !== undefined && (
                <div className="flex flex-col p-4 rounded-lg border bg-card">
                  <div className="flex items-center gap-2 mb-2">
                    <TrendingUp className="w-5 h-5 text-primary" />
                    <span className="text-sm text-muted-foreground">
                      Auditeurs uniques
                    </span>
                  </div>
                  <span className="text-2xl font-bold">
                    {analytics.unique_listeners.toLocaleString()}
                  </span>
                  <span className="text-xs text-muted-foreground mt-1">
                    Utilisateurs ayant écouté la playlist
                  </span>
                </div>
              )}

              {analytics.average_completion_rate !== undefined && (
                <div className="flex flex-col p-4 rounded-lg border bg-card">
                  <div className="flex items-center gap-2 mb-2">
                    <TrendingUp className="w-5 h-5 text-primary" />
                    <span className="text-sm text-muted-foreground">
                      Taux de complétion
                    </span>
                  </div>
                  <span className="text-2xl font-bold">
                    {analytics.average_completion_rate.toFixed(1)}%
                  </span>
                  <span className="text-xs text-muted-foreground mt-1">
                    Pourcentage moyen d'écoute
                  </span>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Message si aucune statistique */}
      {analytics.play_count === 0 &&
        analytics.share_count === 0 &&
        analytics.like_count === 0 &&
        analytics.view_count === 0 && (
          <Card>
            <CardContent className="pt-6">
              <div className="text-center text-muted-foreground">
                <p>Aucune statistique disponible pour cette playlist.</p>
                <p className="text-sm mt-2">
                  Les statistiques apparaîtront ici une fois que la playlist
                  aura été utilisée.
                </p>
              </div>
            </CardContent>
          </Card>
        )}
    </div>
  );
}
