import { useState, useEffect, useCallback } from 'react';
import {
  getPlaybackSummary,
  PlaybackSummary as PlaybackSummaryType,
} from '../services/playbackAnalyticsService';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Play, Clock, CheckCircle2 } from 'lucide-react';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';

interface PlaybackSummaryProps {
  trackId: string;
  className?: string;
}

/**
 * Composant pour afficher le résumé des analytics de lecture d'un track
 * T0371: Create Playback Analytics Summary Component
 */
export function PlaybackSummary({ trackId, className }: PlaybackSummaryProps) {
  const [summary, setSummary] = useState<PlaybackSummaryType | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadSummary = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getPlaybackSummary(trackId);
      setSummary(data);
    } catch (err: unknown) {
      const apiError = parseApiError(err);
      logger.error('Failed to load playback summary:', {
        message: apiError.message,
      });
      setError(apiError.message);
    } finally {
      setLoading(false);
    }
  };

  // Formater le temps en format lisible (ex: 1h 30min, 5m 15s)
  const formatTime = useCallback((seconds: number): string => {
    if (seconds < 0) return 'N/A';
    if (seconds < 60) {
      return `${Math.round(seconds)}s`;
    }
    const minutes = Math.floor(seconds / 60);
    const secs = Math.round(seconds % 60);
    if (minutes < 60) {
      return secs > 0 ? `${minutes}m ${secs}s` : `${minutes}m`;
    }
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return mins > 0 ? `${hours}h ${mins}min` : `${hours}h`;
  }, []);

  // Formater le nombre avec séparateur de milliers
  const formatNumber = useCallback((num: number): string => {
    return new Intl.NumberFormat('fr-FR').format(num);
  }, []);

  if (loading) {
    return (
      <Card className={className}>
        <CardHeader>
          <CardTitle>Résumé des Analytics</CardTitle>
          <CardDescription>
            Statistiques principales de lecture du track
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[200px]">
            <LoadingSpinner />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className={className}>
        <CardHeader>
          <CardTitle>Résumé des Analytics</CardTitle>
          <CardDescription>
            Statistiques principales de lecture du track
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[200px] text-muted-foreground">
            {error}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!summary) {
    return (
      <Card className={className}>
        <CardHeader>
          <CardTitle>Résumé des Analytics</CardTitle>
          <CardDescription>
            Statistiques principales de lecture du track
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[200px] text-muted-foreground">
            Aucune donnée de lecture disponible pour ce track.
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className={className}>
      <Card>
        <CardHeader>
          <CardTitle>Résumé des Analytics</CardTitle>
          <CardDescription>
            Statistiques principales de lecture du track
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Card: Total Plays */}
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">
                  Lectures totales
                </CardTitle>
                <Play className="h-4 w-4 text-blue-600" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">
                  {formatNumber(summary.total_plays)}
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  Nombre total de sessions de lecture
                </p>
              </CardContent>
            </Card>

            {/* Card: Average Play Time */}
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">
                  Temps de lecture moyen
                </CardTitle>
                <Clock className="h-4 w-4 text-green-600" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">
                  {formatTime(summary.average_play_time)}
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  Durée moyenne par session
                </p>
              </CardContent>
            </Card>

            {/* Card: Completion Rate */}
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">
                  Taux de complétion
                </CardTitle>
                <CheckCircle2 className="h-4 w-4 text-purple-600" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">
                  {summary.completion_rate.toFixed(1)}%
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  Sessions complétées (&gt;90%)
                </p>
              </CardContent>
            </Card>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
