'use client';

import { useState } from 'react';
import { useWeeklyMetrics, useVelocityTrends } from '@/hooks/use-metrics';
import { getToday } from '@/lib/date-utils';
import { Card, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { MetricsOverview } from './charts/MetricsOverview';
import { MetricsMainCharts } from './charts/MetricsMainCharts';
import { MetricsDistributionCharts } from './charts/MetricsDistributionCharts';
import { MetricsVelocitySection } from './charts/MetricsVelocitySection';
import { MetricsProductivitySection } from './charts/MetricsProductivitySection';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';
import { Emoji } from '@/components/ui/Emoji';

interface MetricsTabProps {
  className?: string;
}

export function MetricsTab({ className }: MetricsTabProps) {
  const [selectedDate] = useState<Date>(getToday());
  const [weeksBack, setWeeksBack] = useState(4);

  const {
    metrics,
    loading: metricsLoading,
    error: metricsError,
    refetch: refetchMetrics,
  } = useWeeklyMetrics(selectedDate);
  const {
    trends,
    loading: trendsLoading,
    error: trendsError,
    refetch: refetchTrends,
  } = useVelocityTrends(weeksBack);

  const handleRefresh = () => {
    refetchMetrics();
    refetchTrends();
  };

  const formatPeriod = () => {
    if (!metrics) return '';
    return `7 derniers jours (${format(metrics.period.start, 'dd MMM', { locale: fr })} - ${format(metrics.period.end, 'dd MMM yyyy', { locale: fr })})`;
  };

  if (metricsError || trendsError) {
    return (
      <div className={className}>
        <Card>
          <CardContent className="p-6 text-center">
            <p className="text-red-500 mb-4">
              <Emoji emoji="❌" /> Erreur lors du chargement des métriques
            </p>
            <p className="text-sm text-[var(--muted-foreground)] mb-4">
              {metricsError || trendsError}
            </p>
            <Button onClick={handleRefresh} variant="secondary" size="sm">
              <Emoji emoji="🔄" /> Réessayer
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className={className}>
      {/* Header avec période et contrôles */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h2 className="text-xl font-bold text-[var(--foreground)]">
            <Emoji emoji="📊" /> Métriques & Analytics
          </h2>
          <p className="text-[var(--muted-foreground)]">{formatPeriod()}</p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            onClick={handleRefresh}
            variant="secondary"
            size="sm"
            disabled={metricsLoading || trendsLoading}
          >
            <Emoji emoji="🔄" /> Actualiser
          </Button>
        </div>
      </div>

      {metricsLoading ? (
        <Card>
          <CardContent className="p-6 text-center">
            <div className="animate-pulse">
              <div className="h-4 bg-[var(--border)] rounded w-1/4 mx-auto mb-4"></div>
              <div className="h-32 bg-[var(--border)] rounded"></div>
            </div>
            <p className="text-[var(--muted-foreground)] mt-4">
              Chargement des métriques...
            </p>
          </CardContent>
        </Card>
      ) : metrics ? (
        <div className="space-y-6">
          {/* Vue d'ensemble rapide */}
          <MetricsOverview metrics={metrics} />

          {/* Graphiques principaux */}
          <MetricsMainCharts metrics={metrics} />

          {/* Distribution et priorités */}
          <MetricsDistributionCharts metrics={metrics} />

          {/* Tendances de vélocité */}
          <MetricsVelocitySection
            trends={trends}
            trendsLoading={trendsLoading}
            weeksBack={weeksBack}
            onWeeksBackChange={setWeeksBack}
          />

          {/* Analyses de productivité */}
          <MetricsProductivitySection metrics={metrics} />
        </div>
      ) : null}
    </div>
  );
}
