import { useState, useEffect, useMemo } from 'react';
import {
  getPlaybackHeatmap,
  PlaybackHeatmap as PlaybackHeatmapType,
} from '../services/playbackAnalyticsService';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { cn } from '@/lib/utils';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';

interface PlaybackHeatmapProps {
  trackId: string;
  className?: string;
  segmentSize?: number; // Taille des segments en secondes (optionnel)
}

/**
 * Composant pour afficher la heatmap des analytics de lecture d'un track
 * T0377: Create Playback Analytics Heatmap Component
 */
export function PlaybackHeatmap({
  trackId,
  className,
  segmentSize = 5,
}: PlaybackHeatmapProps) {
  const [heatmap, setHeatmap] = useState<PlaybackHeatmapType | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!trackId) {
      setHeatmap(null);
      setLoading(false);
      return;
    }

    loadHeatmap();
  }, [trackId, segmentSize]);

  const loadHeatmap = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getPlaybackHeatmap(trackId, segmentSize);
      setHeatmap(data);
    } catch (err: unknown) {
      const apiError = parseApiError(err);
      logger.error('Failed to load playback heatmap:', {
        message: apiError.message,
      });
      setError(apiError.message);
    } finally {
      setLoading(false);
    }
  };

  // Formater le temps en format lisible (ex: 1m 30s, 5s)
  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);
    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`;
  };

  // Calculer la couleur en fonction de l'intensité
  const getIntensityColor = (intensity: number): string => {
    // Gradient de bleu (faible) à rouge (fort)
    // intensity: 0-1
    if (intensity === 0) {
      return 'bg-gray-100'; // Pas d'écoute
    }
    if (intensity < 0.2) {
      return 'bg-blue-100'; // Faible intensité
    }
    if (intensity < 0.4) {
      return 'bg-blue-300'; // Intensité faible-moyenne
    }
    if (intensity < 0.6) {
      return 'bg-green-300'; // Intensité moyenne
    }
    if (intensity < 0.8) {
      return 'bg-yellow-300'; // Intensité moyenne-forte
    }
    return 'bg-red-400'; // Forte intensité
  };

  // Calculer la couleur de bordure pour les zones skip
  const getSkipBorderColor = (
    skipCount: number,
    listenCount: number,
  ): string => {
    if (skipCount === 0 || listenCount === 0) {
      return '';
    }
    const skipRatio = skipCount / listenCount;
    if (skipRatio > 0.5) {
      return 'border-2 border-red-500'; // Beaucoup de skips
    }
    if (skipRatio > 0.3) {
      return 'border-2 border-orange-400'; // Skips modérés
    }
    return '';
  };

  // Calculer les statistiques pour l'affichage
  const stats = useMemo(() => {
    if (!heatmap || heatmap.segments.length === 0) {
      return null;
    }

    const totalListens = heatmap.segments.reduce(
      (sum, seg) => sum + seg.listen_count,
      0,
    );
    const totalSkips = heatmap.segments.reduce(
      (sum, seg) => sum + seg.skip_count,
      0,
    );
    const maxIntensitySegment = heatmap.segments.reduce(
      (max, seg) => (seg.intensity > max.intensity ? seg : max),
      heatmap.segments[0],
    );
    const maxSkipSegment = heatmap.segments.reduce(
      (max, seg) => (seg.skip_count > max.skip_count ? seg : max),
      heatmap.segments[0],
    );

    return {
      totalListens,
      totalSkips,
      maxIntensitySegment,
      maxSkipSegment,
    };
  }, [heatmap]);

  if (loading) {
    return (
      <Card className={cn('w-full', className)}>
        <CardHeader>
          <CardTitle className="text-2xl font-semibold leading-none tracking-tight">
            Heatmap de Lecture
          </CardTitle>
          <CardDescription>
            Visualisation des zones les plus écoutées et des patterns d'écoute
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[300px]">
            <LoadingSpinner text="Chargement de la heatmap..." />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className={cn('w-full', className)}>
        <CardHeader>
          <CardTitle className="text-2xl font-semibold leading-none tracking-tight">
            Heatmap de Lecture
          </CardTitle>
          <CardDescription>
            Visualisation des zones les plus écoutées et des patterns d'écoute
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[300px] text-red-500">
            {error}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!heatmap || heatmap.segments.length === 0) {
    return (
      <Card className={cn('w-full', className)}>
        <CardHeader>
          <CardTitle className="text-2xl font-semibold leading-none tracking-tight">
            Heatmap de Lecture
          </CardTitle>
          <CardDescription>
            Visualisation des zones les plus écoutées et des patterns d'écoute
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[300px] text-muted-foreground">
            Aucune donnée de heatmap disponible pour ce track.
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className={cn('w-full', className)}>
      <CardHeader>
        <CardTitle className="text-2xl font-semibold leading-none tracking-tight">
          Heatmap de Lecture
        </CardTitle>
        <CardDescription>
          Visualisation des zones les plus écoutées et des patterns d'écoute
          {heatmap.track_duration > 0 && (
            <span className="ml-2 text-xs">
              (Durée: {formatTime(heatmap.track_duration)}, Segments:{' '}
              {heatmap.segment_size}s)
            </span>
          )}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {/* Statistiques */}
        {stats && (
          <div className="mb-4 grid grid-cols-1 md:grid-cols-4 gap-4 text-sm">
            <div className="p-2 bg-blue-50 rounded">
              <div className="font-semibold text-blue-900">Écoutes totales</div>
              <div className="text-2xl font-bold text-blue-600">
                {stats.totalListens}
              </div>
            </div>
            <div className="p-2 bg-orange-50 rounded">
              <div className="font-semibold text-orange-900">Skips totales</div>
              <div className="text-2xl font-bold text-orange-600">
                {stats.totalSkips}
              </div>
            </div>
            <div className="p-2 bg-green-50 rounded">
              <div className="font-semibold text-green-900">
                Zone la plus écoutée
              </div>
              <div className="text-lg font-bold text-green-600">
                {formatTime(stats.maxIntensitySegment.start_time)} -{' '}
                {formatTime(stats.maxIntensitySegment.end_time)}
              </div>
            </div>
            <div className="p-2 bg-red-50 rounded">
              <div className="font-semibold text-red-900">
                Zone la plus skipée
              </div>
              <div className="text-lg font-bold text-red-600">
                {stats.maxSkipSegment.skip_count > 0 ? (
                  <>
                    {formatTime(stats.maxSkipSegment.start_time)} -{' '}
                    {formatTime(stats.maxSkipSegment.end_time)}
                  </>
                ) : (
                  'Aucune'
                )}
              </div>
            </div>
          </div>
        )}

        {/* Heatmap */}
        <div className="space-y-2">
          <div className="flex items-center justify-between text-xs text-muted-foreground mb-2">
            <span>0s</span>
            <span className="text-center">Intensité d'écoute</span>
            <span>{formatTime(heatmap.track_duration)}</span>
          </div>

          <div className="flex flex-wrap gap-1">
            {heatmap.segments.map((segment, index) => {
              const intensityColor = getIntensityColor(segment.intensity);
              const skipBorder = getSkipBorderColor(
                segment.skip_count,
                segment.listen_count,
              );
              const segmentWidthPercent =
                ((segment.end_time - segment.start_time) /
                  heatmap.track_duration) *
                100;

              return (
                <div
                  key={index}
                  className={cn(
                    'h-8 rounded transition-all hover:scale-105 cursor-pointer relative group',
                    intensityColor,
                    skipBorder,
                  )}
                  style={{ width: `${Math.max(segmentWidthPercent, 0.5)}%` }}
                  title={`${formatTime(segment.start_time)} - ${formatTime(segment.end_time)}
Écoutes: ${segment.listen_count}
Skips: ${segment.skip_count}
Intensité: ${(segment.intensity * 100).toFixed(1)}%`}
                >
                  {/* Tooltip au survol */}
                  <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 hidden group-hover:block z-10 bg-gray-900 text-white text-xs rounded px-2 py-1 whitespace-nowrap">
                    <div>
                      {formatTime(segment.start_time)} -{' '}
                      {formatTime(segment.end_time)}
                    </div>
                    <div>Écoutes: {segment.listen_count}</div>
                    <div>Skips: {segment.skip_count}</div>
                    <div>
                      Intensité: {(segment.intensity * 100).toFixed(1)}%
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Légende */}
          <div className="mt-4 flex items-center justify-between text-xs">
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 bg-gray-100 rounded"></div>
                <span>Non écouté</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 bg-blue-300 rounded"></div>
                <span>Faible</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 bg-green-300 rounded"></div>
                <span>Moyen</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 bg-yellow-300 rounded"></div>
                <span>Élevé</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 bg-red-400 rounded"></div>
                <span>Très élevé</span>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 border-2 border-red-500 rounded"></div>
              <span>Zone skipée</span>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
