import { useState, useEffect } from 'react';
import { getPlaysOverTime, PlayTimePoint } from '../services/trackService';
import { LineChart, LineChartData } from '@/components/charts/LineChart';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { LoadingSpinner } from '@/components/ui/loading-spinner';

interface PlaysChartProps {
  trackId: number;
}

/**
 * PlaysChart Component
 * T0295: Composant pour afficher le graphique des lectures sur une période
 */
export function PlaysChart({ trackId }: PlaysChartProps) {
  const [data, setData] = useState<LineChartData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [interval, setInterval] = useState<'day' | 'week' | 'month'>('day');

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

  const loadData = async () => {
    setLoading(true);
    setError(null);
    try {
      // Calculer les dates (30 derniers jours par défaut)
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - 30);

      const points = await getPlaysOverTime(
        trackId,
        startDate.toISOString(),
        endDate.toISOString(),
        interval
      );

      // Convertir les points en format LineChartData
      const chartData: LineChartData[] = points.map((point) => {
        const date = new Date(point.date);
        let label = '';
        
        switch (interval) {
          case 'hour':
            label = date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
            break;
          case 'day':
            label = date.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit' });
            break;
          case 'week':
            label = `Sem. ${getWeekNumber(date)}`;
            break;
          case 'month':
            label = date.toLocaleDateString('fr-FR', { month: 'short' });
            break;
        }

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

      setData(chartData);
    } catch (err) {
      console.error('Failed to load plays data:', err);
      setError('Impossible de charger les données');
    } finally {
      setLoading(false);
    }
  };

  const getWeekNumber = (date: Date): number => {
    const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
    const dayNum = d.getUTCDay() || 7;
    d.setUTCDate(d.getUTCDate() + 4 - dayNum);
    const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
    return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg font-semibold">Lectures dans le temps</CardTitle>
          <div className="flex gap-2">
            <button
              onClick={() => setInterval('day')}
              className={`px-3 py-1 text-sm rounded-md transition-colors ${
                interval === 'day'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted hover:bg-muted/80'
              }`}
            >
              Jour
            </button>
            <button
              onClick={() => setInterval('week')}
              className={`px-3 py-1 text-sm rounded-md transition-colors ${
                interval === 'week'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted hover:bg-muted/80'
              }`}
            >
              Semaine
            </button>
            <button
              onClick={() => setInterval('month')}
              className={`px-3 py-1 text-sm rounded-md transition-colors ${
                interval === 'month'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted hover:bg-muted/80'
              }`}
            >
              Mois
            </button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex items-center justify-center h-[300px]">
            <LoadingSpinner />
          </div>
        ) : error ? (
          <div className="flex items-center justify-center h-[300px] text-muted-foreground">
            {error}
          </div>
        ) : (
          <LineChart
            data={data}
            xAxisLabel="Date"
            yAxisLabel="Lectures"
            color="#3b82f6"
            height={300}
            showGrid={true}
            showDots={true}
          />
        )}
      </CardContent>
    </Card>
  );
}

