'use client';

import { useState, useEffect, useMemo } from 'react';
import { JiraConfig, JiraAnalytics } from '@/lib/types';
import { useJiraAnalytics } from '@/hooks/useJiraAnalytics';
import { useJiraExport } from '@/hooks/useJiraExport';
import {
  filterAnalyticsByPeriod,
  getPeriodInfo,
  type PeriodFilter,
} from '@/lib/jira-period-filter';
import { Header } from '@/components/ui/Header';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { PeriodSelector, SkeletonGrid, MetricsGrid } from '@/components/ui';
import { AlertBanner } from '@/components/ui/AlertBanner';
import { Tabs } from '@/components/ui/Tabs';
import { VelocityChart } from '@/components/jira/VelocityChart';
import { TeamDistributionChart } from '@/components/jira/TeamDistributionChart';
import { CycleTimeChart } from '@/components/jira/CycleTimeChart';
import { TeamActivityHeatmap } from '@/components/jira/TeamActivityHeatmap';
import { BurndownChart } from '@/components/jira/BurndownChart';
import { ThroughputChart } from '@/components/jira/ThroughputChart';
import { QualityMetrics } from '@/components/jira/QualityMetrics';
import { PredictabilityMetrics } from '@/components/jira/PredictabilityMetrics';
import { CollaborationMatrix } from '@/components/jira/CollaborationMatrix';
import { SprintComparison } from '@/components/jira/SprintComparison';
import AnomalyDetectionPanel from '@/components/jira/AnomalyDetectionPanel';
import FilterBar from '@/components/jira/FilterBar';
import SprintDetailModal, {
  SprintDetails,
} from '@/components/jira/SprintDetailModal';
import { getSprintDetails } from '../../actions/jira-sprint-details';
import { useJiraFilters } from '@/hooks/useJiraFilters';
import { SprintVelocity } from '@/lib/types';
import Link from 'next/link';
import { Emoji } from '@/components/ui/Emoji';

interface JiraDashboardPageClientProps {
  initialJiraConfig: JiraConfig;
  initialAnalytics?: JiraAnalytics | null;
}

export function JiraDashboardPageClient({
  initialJiraConfig,
  initialAnalytics,
}: JiraDashboardPageClientProps) {
  const {
    analytics: rawAnalytics,
    isLoading,
    error,
    loadAnalytics,
    refreshAnalytics,
  } = useJiraAnalytics(initialAnalytics);
  const {
    isExporting,
    error: exportError,
    exportCSV,
    exportJSON,
  } = useJiraExport();
  const {
    availableFilters,
    activeFilters,
    filteredAnalytics,
    applyFilters,
    hasActiveFilters,
  } = useJiraFilters(rawAnalytics);
  const [selectedPeriod, setSelectedPeriod] = useState<PeriodFilter>('current');
  const [selectedSprint, setSelectedSprint] = useState<SprintVelocity | null>(
    null
  );
  const [showSprintModal, setShowSprintModal] = useState(false);
  const [activeTab, setActiveTab] = useState<
    'overview' | 'velocity' | 'analytics' | 'quality'
  >('overview');

  // Filtrer les analytics selon la période sélectionnée et les filtres avancés
  const analytics = useMemo(() => {
    // Si on a des filtres actifs ET des analytics filtrées, utiliser celles-ci
    // Sinon utiliser les analytics brutes
    // Si on est en train de charger les filtres, garder les données originales
    const baseAnalytics =
      hasActiveFilters && filteredAnalytics ? filteredAnalytics : rawAnalytics;
    if (!baseAnalytics) return null;
    return filterAnalyticsByPeriod(baseAnalytics, selectedPeriod);
  }, [rawAnalytics, filteredAnalytics, selectedPeriod, hasActiveFilters]);

  // Informations sur la période pour l'affichage
  const periodInfo = getPeriodInfo(selectedPeriod);

  useEffect(() => {
    // Charger les analytics au montage seulement si Jira est configuré ET qu'on n'a pas déjà des données
    if (
      initialJiraConfig.enabled &&
      initialJiraConfig.projectKey &&
      !initialAnalytics
    ) {
      loadAnalytics();
    }
  }, [
    initialJiraConfig.enabled,
    initialJiraConfig.projectKey,
    loadAnalytics,
    initialAnalytics,
  ]);

  // Gestion du clic sur un sprint
  const handleSprintClick = (sprint: SprintVelocity) => {
    setSelectedSprint(sprint);
    setShowSprintModal(true);
  };

  const handleCloseSprintModal = () => {
    setShowSprintModal(false);
    setSelectedSprint(null);
  };

  const loadSprintDetails = async (
    sprintName: string
  ): Promise<SprintDetails> => {
    const result = await getSprintDetails(sprintName);
    if (result.success && result.data) {
      return result.data;
    } else {
      throw new Error(
        result.error || 'Erreur lors du chargement des détails du sprint'
      );
    }
  };

  // Vérifier si Jira est configuré
  const isJiraConfigured =
    initialJiraConfig.enabled &&
    initialJiraConfig.baseUrl &&
    initialJiraConfig.email &&
    initialJiraConfig.apiToken;

  const hasProjectConfigured = isJiraConfigured && initialJiraConfig.projectKey;

  if (!isJiraConfigured) {
    return (
      <div className="min-h-screen bg-[var(--background)]">
        <Header
          title="TowerControl"
          subtitle="Dashboard Jira - Analytics d'équipe"
        />

        <div className="container mx-auto px-4 py-8">
          <Card className="max-w-2xl mx-auto">
            <CardHeader>
              <h2 className="text-xl font-semibold">
                <Emoji emoji="⚙️" /> Configuration requise
              </h2>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-[var(--muted-foreground)]">
                Jira n&apos;est pas configuré. Vous devez d&apos;abord
                configurer votre connexion Jira pour accéder aux analytics
                d&apos;équipe.
              </p>
              <Link href="/settings/integrations">
                <Button variant="primary">Configurer Jira</Button>
              </Link>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  if (!hasProjectConfigured) {
    return (
      <div className="min-h-screen bg-[var(--background)]">
        <Header
          title="TowerControl"
          subtitle="Dashboard Jira - Analytics d'équipe"
        />

        <div className="container mx-auto px-4 py-8">
          <Card className="max-w-2xl mx-auto">
            <CardHeader>
              <h2 className="text-xl font-semibold">
                <Emoji emoji="🎯" /> Projet requis
              </h2>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-[var(--muted-foreground)]">
                Aucun projet n&apos;est configuré pour les analytics
                d&apos;équipe. Configurez un projet spécifique à surveiller dans
                les paramètres Jira.
              </p>
              <Link href="/settings/integrations">
                <Button variant="primary">Configurer un projet</Button>
              </Link>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[var(--background)]">
      <Header
        title="TowerControl"
        subtitle={`Analytics Jira - Projet ${initialJiraConfig.projectKey}`}
      />

      <div className="container mx-auto px-4 py-4">
        <div className="max-w-7xl mx-auto">
          {/* Breadcrumb */}
          <div className="mb-4 text-sm">
            <Link
              href="/settings"
              className="text-[var(--muted-foreground)] hover:text-[var(--primary)]"
            >
              Paramètres
            </Link>
            <span className="mx-2 text-[var(--muted-foreground)]">/</span>
            <Link
              href="/settings/integrations"
              className="text-[var(--muted-foreground)] hover:text-[var(--primary)]"
            >
              Intégrations
            </Link>
            <span className="mx-2 text-[var(--muted-foreground)]">/</span>
            <span className="text-[var(--foreground)]">Dashboard Jira</span>
          </div>

          {/* Header avec contrôles */}
          <div className="flex items-center justify-between mb-6">
            <div>
              <h1 className="text-2xl font-mono font-bold text-[var(--foreground)] mb-2">
                <Emoji emoji="📊" /> Analytics d&apos;équipe
              </h1>
              <div className="space-y-1">
                <p className="text-[var(--muted-foreground)]">
                  Surveillance en temps réel du projet{' '}
                  {initialJiraConfig.projectKey}
                </p>
                <p className="text-sm text-[var(--primary)] flex items-center gap-1">
                  <span>{periodInfo.icon}</span>
                  <span>{periodInfo.label}</span>
                  <span className="text-[var(--muted-foreground)]">
                    • {periodInfo.description}
                  </span>
                </p>
              </div>
            </div>

            <div className="flex items-center gap-3">
              {/* Sélecteur de période */}
              <PeriodSelector
                options={[
                  { value: '7d', label: '7j' },
                  { value: '30d', label: '30j' },
                  { value: '3m', label: '3m' },
                  { value: 'current', label: 'Sprint' },
                ]}
                selectedValue={selectedPeriod}
                onValueChange={(value) =>
                  setSelectedPeriod(value as PeriodFilter)
                }
              />

              <div className="flex items-center gap-2">
                {analytics && (
                  <>
                    <div className="text-xs text-[var(--muted-foreground)] px-2 py-1 bg-[var(--card)] border border-[var(--border)] rounded">
                      💾 Données en cache
                    </div>

                    {/* Boutons d'export */}
                    <div className="flex items-center gap-1">
                      <Button
                        onClick={exportCSV}
                        disabled={isExporting}
                        variant="ghost"
                        className="text-xs px-2 py-1 h-auto"
                      >
                        {isExporting ? (
                          <Emoji emoji="⏳" />
                        ) : (
                          <Emoji emoji="📊" />
                        )}{' '}
                        CSV
                      </Button>
                      <Button
                        onClick={exportJSON}
                        disabled={isExporting}
                        variant="ghost"
                        className="text-xs px-2 py-1 h-auto"
                      >
                        {isExporting ? '⏳' : '📄'} JSON
                      </Button>
                    </div>
                  </>
                )}

                <Button
                  onClick={refreshAnalytics}
                  disabled={isLoading}
                  variant="secondary"
                >
                  {isLoading ? (
                    <>
                      <Emoji emoji="⏳" /> Actualisation...
                    </>
                  ) : (
                    <>
                      <Emoji emoji="🔄" />
                      &nbsp;Actualiser
                    </>
                  )}
                </Button>
              </div>
            </div>
          </div>

          {/* Contenu principal */}
          {error && (
            <AlertBanner
              title="Erreur"
              items={[{ id: 'error', title: error }]}
              icon="❌"
              variant="error"
              className="mb-6"
            />
          )}

          {exportError && (
            <AlertBanner
              title="Erreur d'export"
              items={[{ id: 'export-error', title: exportError }]}
              icon="⚠️"
              variant="warning"
              className="mb-6"
            />
          )}

          {isLoading && !analytics && <SkeletonGrid count={6} />}

          {analytics && (
            <div className="space-y-6">
              {/* En-tête compact du projet */}
              <Card>
                <CardHeader className="pb-4">
                  <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                    <h2 className="text-lg font-semibold flex items-center gap-2">
                      <Emoji emoji="🎯" /> {analytics.project.name}
                      <span className="text-sm font-normal text-[var(--muted-foreground)]">
                        ({periodInfo.label})
                      </span>
                      {hasActiveFilters && (
                        <Badge className="bg-purple-100 text-purple-800 text-xs">
                          <Emoji emoji="🔍" /> Filtré
                        </Badge>
                      )}
                    </h2>
                    <MetricsGrid
                      metrics={[
                        {
                          title: 'Tickets',
                          value: analytics.project.totalIssues,
                          color: 'primary',
                        },
                        {
                          title: 'Équipe',
                          value: analytics.teamMetrics.totalAssignees,
                          color: 'default',
                        },
                        {
                          title: 'Actifs',
                          value: analytics.teamMetrics.activeAssignees,
                          color: 'success',
                        },
                        {
                          title: 'Points',
                          value: analytics.velocityMetrics.currentSprintPoints,
                          color: 'warning',
                        },
                      ]}
                    />
                  </div>
                </CardHeader>
              </Card>

              {/* Barre de filtres */}
              <FilterBar
                availableFilters={availableFilters}
                activeFilters={activeFilters}
                onFiltersChange={applyFilters}
                isLoading={false}
              />

              {/* Détection d'anomalies */}
              <AnomalyDetectionPanel />

              {/* Onglets de navigation */}
              <Tabs
                items={[
                  { id: 'overview', label: "📊 Vue d'ensemble" },
                  { id: 'velocity', label: '🚀 Vélocité & Sprints' },
                  { id: 'analytics', label: '📈 Analytics avancées' },
                  { id: 'quality', label: '🎯 Qualité & Collaboration' },
                ]}
                activeTab={activeTab}
                onTabChange={(tabId) =>
                  setActiveTab(
                    tabId as 'overview' | 'velocity' | 'analytics' | 'quality'
                  )
                }
              />

              {/* Contenu des onglets */}
              {activeTab === 'overview' && (
                <div className="space-y-6">
                  {/* Info discrète sur le calcul des points */}
                  <div className="text-xs text-[var(--muted-foreground)] bg-[var(--card-column)] px-3 py-2 rounded border border-[var(--border)]">
                    <Emoji emoji="💡" /> <strong>Points :</strong> Utilise les
                    story points Jira si définis, sinon Epic(13), Story(5),
                    Task(3), Bug(2), Subtask(1)
                  </div>

                  {/* Graphiques principaux */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="👥" /> Répartition de l&apos;équipe
                        </h3>
                      </CardHeader>
                      <CardContent>
                        <TeamDistributionChart
                          distribution={
                            analytics.teamMetrics.issuesDistribution
                          }
                          className="h-64"
                        />
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="🚀" /> Vélocité des sprints
                        </h3>
                      </CardHeader>
                      <CardContent>
                        <VelocityChart
                          sprintHistory={
                            analytics.velocityMetrics.sprintHistory
                          }
                          className="h-64"
                          onSprintClick={handleSprintClick}
                        />
                      </CardContent>
                    </Card>
                  </div>

                  {/* Métriques de temps et cycle time */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="⏱️" /> Cycle Time par type
                        </h3>
                      </CardHeader>
                      <CardContent>
                        <CycleTimeChart
                          cycleTimeByType={
                            analytics.cycleTimeMetrics.cycleTimeByType
                          }
                          className="h-64"
                        />
                        <div className="mt-4 text-center">
                          <div className="text-2xl font-bold text-[var(--primary)]">
                            {analytics.cycleTimeMetrics.averageCycleTime}
                          </div>
                          <div className="text-sm text-[var(--muted-foreground)]">
                            jours en moyenne globale
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">🚀 Vélocité</h3>
                      </CardHeader>
                      <CardContent>
                        <div className="mb-4">
                          <div className="text-3xl font-bold text-green-500">
                            {analytics.velocityMetrics.averageVelocity}
                          </div>
                          <div className="text-sm text-[var(--muted-foreground)]">
                            points par sprint
                          </div>
                        </div>
                        <div className="space-y-2">
                          {analytics.velocityMetrics.sprintHistory.map(
                            (sprint) => (
                              <div key={sprint.sprintName} className="text-sm">
                                <div className="flex justify-between">
                                  <span>{sprint.sprintName}</span>
                                  <span className="font-mono">
                                    {sprint.completedPoints}/
                                    {sprint.plannedPoints}
                                  </span>
                                </div>
                                <div className="w-full bg-[var(--muted)] rounded-full h-1.5 mt-1">
                                  <div
                                    className="bg-green-500 h-1.5 rounded-full"
                                    style={{
                                      width: `${sprint.completionRate}%`,
                                    }}
                                  ></div>
                                </div>
                              </div>
                            )
                          )}
                        </div>
                      </CardContent>
                    </Card>
                  </div>

                  {/* Métriques avancées */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="📉" /> Burndown Chart
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-96 overflow-hidden">
                          <BurndownChart
                            sprintHistory={
                              analytics.velocityMetrics.sprintHistory
                            }
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="📈" /> Throughput
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-96 overflow-hidden">
                          <ThroughputChart
                            sprintHistory={
                              analytics.velocityMetrics.sprintHistory
                            }
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>
                  </div>

                  {/* Métriques de qualité */}
                  <Card>
                    <CardHeader>
                      <h3 className="font-semibold">
                        <Emoji emoji="🎯" /> Métriques de qualité
                      </h3>
                    </CardHeader>
                    <CardContent className="p-4">
                      <div className="w-full overflow-hidden">
                        <QualityMetrics
                          analytics={analytics}
                          className="min-h-96 w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>

                  {/* Métriques de predictabilité */}
                  <Card>
                    <CardHeader>
                      <h3 className="font-semibold">
                        <Emoji emoji="📊" /> Predictabilité
                      </h3>
                    </CardHeader>
                    <CardContent className="p-4">
                      <div className="w-full overflow-hidden">
                        <PredictabilityMetrics
                          sprintHistory={
                            analytics.velocityMetrics.sprintHistory
                          }
                          className="h-auto w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>

                  {/* Matrice de collaboration - ligne entière */}
                  <Card>
                    <CardHeader>
                      <h3 className="font-semibold">
                        <Emoji emoji="🤝" /> Matrice de collaboration
                      </h3>
                    </CardHeader>
                    <CardContent className="p-4">
                      <div className="w-full overflow-hidden">
                        <CollaborationMatrix
                          analytics={analytics}
                          className="h-auto w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>

                  {/* Comparaison inter-sprints */}
                  <Card>
                    <CardHeader>
                      <h3 className="font-semibold">
                        <Emoji emoji="📊" /> Comparaison inter-sprints
                      </h3>
                    </CardHeader>
                    <CardContent className="p-4">
                      <div className="w-full overflow-hidden">
                        <SprintComparison
                          sprintHistory={
                            analytics.velocityMetrics.sprintHistory
                          }
                          className="h-auto w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>

                  {/* Heatmap d'activité de l'équipe */}
                  <Card>
                    <CardHeader>
                      <h3 className="font-semibold">
                        <Emoji emoji="🔥" /> Heatmap d&apos;activité de
                        l&apos;équipe
                      </h3>
                    </CardHeader>
                    <CardContent className="p-4">
                      <div className="w-full overflow-hidden">
                        <TeamActivityHeatmap
                          workloadByAssignee={
                            analytics.workInProgress.byAssignee
                          }
                          statusDistribution={analytics.workInProgress.byStatus}
                          className="min-h-96 w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>
                </div>
              )}

              {activeTab === 'velocity' && (
                <div className="space-y-6">
                  {/* Graphique de vélocité */}
                  <Card>
                    <CardHeader>
                      <h3 className="font-semibold">
                        <Emoji emoji="🚀" /> Vélocité des sprints
                      </h3>
                    </CardHeader>
                    <CardContent className="p-4">
                      <div className="w-full h-64 overflow-hidden">
                        <VelocityChart
                          sprintHistory={
                            analytics.velocityMetrics.sprintHistory
                          }
                          className="h-full w-full"
                          onSprintClick={handleSprintClick}
                        />
                      </div>
                    </CardContent>
                  </Card>

                  {/* Burndown et Throughput */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="📉" /> Burndown Chart
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-96 overflow-hidden">
                          <BurndownChart
                            sprintHistory={
                              analytics.velocityMetrics.sprintHistory
                            }
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="📊" /> Throughput
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-96 overflow-hidden">
                          <ThroughputChart
                            sprintHistory={
                              analytics.velocityMetrics.sprintHistory
                            }
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>
                  </div>

                  {/* Comparaison des sprints */}
                  <Card>
                    <CardHeader>
                      <h3 className="font-semibold">
                        <Emoji emoji="📊" /> Comparaison des sprints
                      </h3>
                    </CardHeader>
                    <CardContent className="p-4">
                      <div className="w-full overflow-hidden">
                        <SprintComparison
                          sprintHistory={
                            analytics.velocityMetrics.sprintHistory
                          }
                          className="h-auto w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>
                </div>
              )}

              {activeTab === 'analytics' && (
                <div className="space-y-6">
                  {/* Métriques de temps et cycle time */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="⏱️" /> Cycle Time par type
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-64 overflow-hidden">
                          <CycleTimeChart
                            cycleTimeByType={
                              analytics.cycleTimeMetrics.cycleTimeByType
                            }
                            className="h-full w-full"
                          />
                        </div>
                        <div className="mt-4 text-center">
                          <div className="text-2xl font-bold text-[var(--primary)]">
                            {analytics.cycleTimeMetrics.averageCycleTime.toFixed(
                              1
                            )}
                          </div>
                          <div className="text-sm text-[var(--muted-foreground)]">
                            Cycle time moyen (jours)
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          🔥 Heatmap d&apos;activité
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-64 overflow-hidden">
                          <TeamActivityHeatmap
                            workloadByAssignee={
                              analytics.workInProgress.byAssignee
                            }
                            statusDistribution={
                              analytics.workInProgress.byStatus
                            }
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>
                  </div>

                  {/* Métriques avancées */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="🎯" /> Métriques de qualité
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-64 overflow-hidden">
                          <QualityMetrics
                            analytics={analytics}
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="📈" /> Predictabilité
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-64 overflow-hidden">
                          <PredictabilityMetrics
                            sprintHistory={
                              analytics.velocityMetrics.sprintHistory
                            }
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>
                  </div>
                </div>
              )}

              {activeTab === 'quality' && (
                <div className="space-y-6">
                  {/* Collaboration et équipe */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="👥" /> Répartition de l&apos;équipe
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-64 overflow-hidden">
                          <TeamDistributionChart
                            distribution={
                              analytics.teamMetrics.issuesDistribution
                            }
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <h3 className="font-semibold">
                          <Emoji emoji="🤝" /> Matrice de collaboration
                        </h3>
                      </CardHeader>
                      <CardContent className="p-4">
                        <div className="w-full h-64 overflow-hidden">
                          <CollaborationMatrix
                            analytics={analytics}
                            className="h-full w-full"
                          />
                        </div>
                      </CardContent>
                    </Card>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Modal de détail de sprint */}
      <SprintDetailModal
        isOpen={showSprintModal}
        onClose={handleCloseSprintModal}
        sprint={selectedSprint}
        onLoadSprintDetails={loadSprintDetails}
      />
    </div>
  );
}
