import { useState, useEffect } from 'react';
import { getBitrateAnalytics, BitrateAnalytics } from '../services/bitrateService';
import { LineChart, LineChartData } from '@/components/charts/LineChart';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Badge } from '@/components/ui/badge';

interface BitrateAnalyticsProps {
  trackId: number;
}

/**
 * Composant pour afficher les analytics d'adaptation de bitrate
 * T0355: Create Bitrate Adaptation Frontend Analytics Component
 */
export function BitrateAnalytics({ trackId }: BitrateAnalyticsProps) {
  const [analytics, setAnalytics] = useState<BitrateAnalytics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadAnalytics = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getBitrateAnalytics(trackId);
      setAnalytics(data);
    } catch (err: any) {
      console.error('Failed to load bitrate analytics:', err);
      setError(err.message || 'Impossible de charger les analytics');
    } finally {
      setLoading(false);
    }
  };

  // Convertir les données d'évolution en format LineChartData
  const getChartData = (): LineChartData[] => {
    if (!analytics || analytics.adaptations_over_time.length === 0) {
      return [];
    }

    return analytics.adaptations_over_time.map((point) => {
      const date = new Date(point.date);
      const label = date.toLocaleDateString('fr-FR', { 
        day: '2-digit', 
        month: '2-digit' 
      });

      return {
        label,
        value: point.count,
      };
    });
  };

  // Formater le nom de la raison
  const formatReason = (reason: string): string => {
    const reasonMap: Record<string, string> = {
      network_slow: 'Réseau lent',
      network_fast: 'Réseau rapide',
      buffer_low: 'Buffer faible',
      user_selected: 'Sélection utilisateur',
    };
    return reasonMap[reason] || reason;
  };

  // Formater la bande passante
  const formatBandwidth = (bandwidth?: number): string => {
    if (!bandwidth) return 'N/A';
    if (bandwidth >= 1000000) {
      return `${(bandwidth / 1000000).toFixed(2)} Mbps`;
    } else if (bandwidth >= 1000) {
      return `${(bandwidth / 1000).toFixed(2)} Kbps`;
    }
    return `${bandwidth} bps`;
  };

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Analytics d'adaptation de bitrate</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[300px]">
            <LoadingSpinner />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Analytics d'adaptation de bitrate</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[300px] text-muted-foreground">
            {error}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!analytics) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Analytics d'adaptation de bitrate</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[300px] text-muted-foreground">
            Aucune donnée disponible
          </div>
        </CardContent>
      </Card>
    );
  }

  const chartData = getChartData();

  return (
    <div className="space-y-4">
      {/* Statistiques générales */}
      <Card>
        <CardHeader>
          <CardTitle>Statistiques d'adaptation</CardTitle>
          <CardDescription>
            Vue d'ensemble des adaptations de bitrate pour ce track
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">Total d'adaptations</span>
              <span className="text-2xl font-bold">{analytics.total_adaptations}</span>
            </div>
            {analytics.average_bandwidth && (
              <div className="flex flex-col">
                <span className="text-sm text-muted-foreground">Bande passante moyenne</span>
                <span className="text-2xl font-bold">
                  {formatBandwidth(analytics.average_bandwidth)}
                </span>
              </div>
            )}
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">Raisons différentes</span>
              <span className="text-2xl font-bold">{Object.keys(analytics.reasons).length}</span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Graphique d'évolution */}
      {chartData.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Évolution des adaptations</CardTitle>
            <CardDescription>
              Nombre d'adaptations par jour
            </CardDescription>
          </CardHeader>
          <CardContent>
            <LineChart
              data={chartData}
              xAxisLabel="Date"
              yAxisLabel="Nombre d'adaptations"
              color="#3b82f6"
              height={300}
              showGrid={true}
              showDots={true}
            />
          </CardContent>
        </Card>
      )}

      {/* Répartition par raison */}
      {Object.keys(analytics.reasons).length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Répartition par raison</CardTitle>
            <CardDescription>
              Nombre d'adaptations selon la raison
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {Object.entries(analytics.reasons)
                .sort(([, a], [, b]) => b - a)
                .map(([reason, count]) => {
                  const percentage = analytics.total_adaptations > 0
                    ? ((count / analytics.total_adaptations) * 100).toFixed(1)
                    : '0';
                  
                  return (
                    <div key={reason} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">{formatReason(reason)}</Badge>
                        <span className="text-sm text-muted-foreground">
                          {count} adaptation{count > 1 ? 's' : ''}
                        </span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-32 bg-muted rounded-full h-2">
                          <div
                            className="bg-primary h-2 rounded-full"
                            style={{ width: `${percentage}%` }}
                          />
                        </div>
                        <span className="text-sm font-medium w-12 text-right">
                          {percentage}%
                        </span>
                      </div>
                    </div>
                  );
                })}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Message si aucune donnée */}
      {analytics.total_adaptations === 0 && (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center text-muted-foreground">
              <p>Aucune adaptation de bitrate enregistrée pour ce track.</p>
              <p className="text-sm mt-2">
                Les adaptations seront affichées ici une fois que le streaming aura commencé.
              </p>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

