import { useState, useEffect } from 'react';
import {
  getPlaybackDashboard,
  PlaybackDashboardData,
} from '../services/playbackAnalyticsService';
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 { TrendingUp, TrendingDown, Minus } from 'lucide-react';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';

interface PlaybackDashboardProps {
  trackId: string;
}

/**
 * Composant pour afficher le dashboard d'analytics de lecture
 * T0364: Create Playback Analytics Dashboard Component
 */
export function PlaybackDashboard({ trackId }: PlaybackDashboardProps) {
  const [dashboard, setDashboard] = useState<PlaybackDashboardData | null>(
    null,
  );
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

  // Convertir les données de séries temporelles en format LineChartData
  const getSessionsChartData = (): LineChartData[] => {
    if (!dashboard || dashboard.time_series.length === 0) {
      return [];
    }

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

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

  const getPlayTimeChartData = (): LineChartData[] => {
    if (!dashboard || dashboard.time_series.length === 0) {
      return [];
    }

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

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

  const getCompletionChartData = (): LineChartData[] => {
    if (!dashboard || dashboard.time_series.length === 0) {
      return [];
    }

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

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

  // Formater le temps en secondes en format lisible
  const formatTime = (seconds: number): string => {
    if (seconds < 60) {
      return `${Math.round(seconds)}s`;
    }
    const minutes = Math.floor(seconds / 60);
    const secs = Math.round(seconds % 60);
    return `${minutes}m ${secs}s`;
  };

  // Formater le temps total en format lisible
  const formatTotalTime = (seconds: number): string => {
    if (seconds < 3600) {
      const minutes = Math.floor(seconds / 60);
      return `${minutes} min`;
    }
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${hours}h ${minutes}min`;
  };

  // Afficher une tendance avec icône
  const renderTrend = (value: number, label: string) => {
    const isPositive = value > 0;
    const isNegative = value < 0;
    const isNeutral = value === 0;

    return (
      <div className="flex items-center gap-2">
        <span className="text-sm text-muted-foreground">{label}</span>
        <div className="flex items-center gap-1">
          {isPositive && <TrendingUp className="h-4 w-4 text-green-500" />}
          {isNegative && <TrendingDown className="h-4 w-4 text-red-500" />}
          {isNeutral && <Minus className="h-4 w-4 text-muted-foreground" />}
          <span
            className={`text-sm font-medium ${
              isPositive
                ? 'text-green-500'
                : isNegative
                  ? 'text-red-500'
                  : 'text-muted-foreground'
            }`}
          >
            {isPositive ? '+' : ''}
            {value.toFixed(1)}%
          </span>
        </div>
      </div>
    );
  };

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

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

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

  const sessionsChartData = getSessionsChartData();
  const playTimeChartData = getPlayTimeChartData();
  const completionChartData = getCompletionChartData();

  return (
    <div className="space-y-4">
      {/* Statistiques générales */}
      <Card>
        <CardHeader>
          <CardTitle>Statistiques générales</CardTitle>
          <CardDescription>
            Vue d'ensemble des analytics de lecture pour ce track
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">
                Total de sessions
              </span>
              <span className="text-2xl font-bold">
                {dashboard.stats.total_sessions}
              </span>
            </div>
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">
                Temps de lecture total
              </span>
              <span className="text-2xl font-bold">
                {formatTotalTime(dashboard.stats.total_play_time)}
              </span>
            </div>
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">
                Temps moyen par session
              </span>
              <span className="text-2xl font-bold">
                {formatTime(dashboard.stats.average_play_time)}
              </span>
            </div>
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">
                Taux de complétion moyen
              </span>
              <span className="text-2xl font-bold">
                {dashboard.stats.average_completion.toFixed(1)}%
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tendances */}
      <Card>
        <CardHeader>
          <CardTitle>Tendances (7 derniers jours)</CardTitle>
          <CardDescription>
            Évolution par rapport aux 7 jours précédents
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {renderTrend(dashboard.trends.sessions_trend, 'Sessions')}
            {renderTrend(dashboard.trends.play_time_trend, 'Temps de lecture')}
            {renderTrend(
              dashboard.trends.completion_trend,
              'Taux de complétion',
            )}
          </div>
          <div className="mt-4 pt-4 border-t">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="flex flex-col">
                <span className="text-sm text-muted-foreground">
                  Sessions (7 jours)
                </span>
                <span className="text-lg font-semibold">
                  {dashboard.trends.total_sessions_7days}
                </span>
              </div>
              <div className="flex flex-col">
                <span className="text-sm text-muted-foreground">
                  Sessions (30 jours)
                </span>
                <span className="text-lg font-semibold">
                  {dashboard.trends.total_sessions_30days}
                </span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Graphique des sessions */}
      {sessionsChartData.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Évolution des sessions</CardTitle>
            <CardDescription>
              Nombre de sessions par jour (30 derniers jours)
            </CardDescription>
          </CardHeader>
          <CardContent>
            <LineChart
              data={sessionsChartData}
              xAxisLabel="Date"
              yAxisLabel="Nombre de sessions"
              color="#3b82f6"
              height={300}
              showGrid={true}
              showDots={true}
            />
          </CardContent>
        </Card>
      )}

      {/* Graphique du temps de lecture */}
      {playTimeChartData.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Évolution du temps de lecture moyen</CardTitle>
            <CardDescription>
              Temps de lecture moyen par jour (30 derniers jours)
            </CardDescription>
          </CardHeader>
          <CardContent>
            <LineChart
              data={playTimeChartData}
              xAxisLabel="Date"
              yAxisLabel="Temps moyen (secondes)"
              color="#10b981"
              height={300}
              showGrid={true}
              showDots={true}
            />
          </CardContent>
        </Card>
      )}

      {/* Graphique du taux de complétion */}
      {completionChartData.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Évolution du taux de complétion</CardTitle>
            <CardDescription>
              Taux de complétion moyen par jour (30 derniers jours)
            </CardDescription>
          </CardHeader>
          <CardContent>
            <LineChart
              data={completionChartData}
              xAxisLabel="Date"
              yAxisLabel="Taux de complétion (%)"
              color="#f59e0b"
              height={300}
              showGrid={true}
              showDots={true}
            />
          </CardContent>
        </Card>
      )}

      {/* Statistiques détaillées */}
      <Card>
        <CardHeader>
          <CardTitle>Statistiques détaillées</CardTitle>
          <CardDescription>
            Métriques supplémentaires sur les sessions de lecture
          </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">
                Pauses totales
              </span>
              <span className="text-xl font-semibold">
                {dashboard.stats.total_pauses}
              </span>
              <span className="text-xs text-muted-foreground mt-1">
                Moyenne: {dashboard.stats.average_pauses.toFixed(1)} par session
              </span>
            </div>
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">
                Sauts (seeks) totaux
              </span>
              <span className="text-xl font-semibold">
                {dashboard.stats.total_seeks}
              </span>
              <span className="text-xs text-muted-foreground mt-1">
                Moyenne: {dashboard.stats.average_seeks.toFixed(1)} par session
              </span>
            </div>
            <div className="flex flex-col">
              <span className="text-sm text-muted-foreground">
                Taux de complétion
              </span>
              <span className="text-xl font-semibold">
                {dashboard.stats.completion_rate.toFixed(1)}%
              </span>
              <span className="text-xs text-muted-foreground mt-1">
                Sessions complétées (&gt;90%)
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Message si aucune donnée */}
      {dashboard.stats.total_sessions === 0 && (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center text-muted-foreground">
              <p>Aucune session de lecture enregistrée pour ce track.</p>
              <p className="text-sm mt-2">
                Les analytics seront affichés ici une fois que les utilisateurs
                auront commencé à écouter ce track.
              </p>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
