'use client';

import { useState } from 'react';
import { WeeklySummary, WeeklyActivity, PERIOD_OPTIONS, PeriodOption } from '@/services/weekly-summary';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { VelocityMetrics } from './VelocityMetrics';
import { CategoryBreakdown } from './CategoryBreakdown';
import { PeriodSelector } from './PeriodSelector';
import { PDFExportService } from '@/services/pdf-export';

interface WeeklySummaryClientProps {
  initialSummary: WeeklySummary;
}

export default function WeeklySummaryClient({ initialSummary }: WeeklySummaryClientProps) {
  const [summary, setSummary] = useState<WeeklySummary>(initialSummary);
  const [selectedDay, setSelectedDay] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isExportingPDF, setIsExportingPDF] = useState(false);
  const [currentPeriod, setCurrentPeriod] = useState<PeriodOption>(PERIOD_OPTIONS[0]);
  const [activeTab, setActiveTab] = useState<string>('all');

  const handlePeriodChange = async (newPeriod: PeriodOption) => {
    setCurrentPeriod(newPeriod);
    setIsRefreshing(true);
    
    try {
      // Appel API pour récupérer les données de la nouvelle période
      const response = await fetch(`/api/weekly-summary?period=${newPeriod.days}`);
      if (response.ok) {
        const newSummary = await response.json();
        setSummary(newSummary);
      } else {
        console.error('Erreur lors du changement de période');
      }
    } catch (error) {
      console.error('Erreur lors du changement de période:', error);
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleRefresh = async () => {
    setIsRefreshing(true);
    // Recharger la page pour refaire le fetch côté serveur
    window.location.reload();
  };

  const handleExportPDF = async () => {
    setIsExportingPDF(true);
    try {
      await PDFExportService.exportWeeklySummary(summary);
    } catch (error) {
      console.error('Erreur lors de l\'export PDF:', error);
      alert('Erreur lors de la génération du PDF');
    } finally {
      setIsExportingPDF(false);
    }
  };

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleDateString('fr-FR', { 
      weekday: 'long', 
      day: 'numeric', 
      month: 'long' 
    });
  };

  const getActivityIcon = (activity: WeeklyActivity) => {
    if (activity.type === 'checkbox') {
      return activity.completed ? '✅' : '☐';
    }
    return activity.completed ? '🎯' : '📝';
  };

  const getActivityTypeLabel = (type: 'checkbox' | 'task') => {
    return type === 'checkbox' ? 'Daily' : 'Tâche';
  };

  // Obtenir les catégories disponibles
  const availableCategories = Object.keys(summary.categoryBreakdown).filter(
    categoryName => summary.categoryBreakdown[categoryName].count > 0
  );

  // Fonction pour catégoriser une activité
  const getActivityCategory = (activity: WeeklyActivity): string => {
    // Logique simple pour associer une activité à une catégorie
    // En production, cette logique devrait être dans un service
    const title = activity.title.toLowerCase();
    
    if (title.includes('meeting') || title.includes('réunion') || title.includes('call') || title.includes('standup')) {
      return 'Meeting';
    }
    if (title.includes('dev') || title.includes('code') || title.includes('bug') || title.includes('fix') || title.includes('feature')) {
      return 'Dev';
    }
    if (title.includes('admin') || title.includes('email') || title.includes('report') || title.includes('planning')) {
      return 'Admin';
    }
    if (title.includes('learn') || title.includes('study') || title.includes('formation') || title.includes('tutorial')) {
      return 'Learning';
    }
    return 'Other';
  };

  // Filtrer les activités
  let filteredActivities = selectedDay 
    ? summary.activities.filter(a => a.dayName === selectedDay)
    : summary.activities;

  // Filtrer par catégorie si ce n'est pas "all"
  if (activeTab !== 'all') {
    filteredActivities = filteredActivities.filter(activity => 
      getActivityCategory(activity) === activeTab
    );
  }

  return (
    <div className="space-y-6">
      {/* Sélecteur de période */}
      <PeriodSelector 
        currentPeriod={currentPeriod}
        onPeriodChange={handlePeriodChange}
        comparison={summary.periodComparison}
        isLoading={isRefreshing}
      />

      {/* Métriques de vélocité */}
      <VelocityMetrics velocity={summary.velocity} />

      {/* Onglets par catégorie */}
      <div className="border-b border-[var(--border)]">
        <nav className="flex space-x-8 overflow-x-auto">
          <button
            onClick={() => setActiveTab('all')}
            className={`py-3 px-1 border-b-2 font-medium text-sm transition-colors whitespace-nowrap ${
              activeTab === 'all'
                ? 'border-[var(--primary)] text-[var(--primary)]'
                : 'border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:border-[var(--border)]'
            }`}
          >
            📊 Vue d&apos;ensemble
          </button>
          {availableCategories.map(categoryName => {
            const categoryData = summary.categoryBreakdown[categoryName];
            return (
              <button
                key={categoryName}
                onClick={() => setActiveTab(categoryName)}
                className={`py-3 px-1 border-b-2 font-medium text-sm transition-colors whitespace-nowrap flex items-center gap-2 ${
                  activeTab === categoryName
                    ? 'border-[var(--primary)] text-[var(--primary)]'
                    : 'border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:border-[var(--border)]'
                }`}
              >
                <span>{categoryData.icon}</span>
                <span>{categoryName}</span>
                <Badge className="bg-[var(--primary)]/10 text-[var(--primary)] text-xs">
                  {categoryData.count}
                </Badge>
              </button>
            );
          })}
        </nav>
      </div>

      {/* Contenu de l'onglet sélectionné */}
      {activeTab === 'all' && (
        <>
          {/* Répartition par catégorie */}
          <CategoryBreakdown 
            categoryData={summary.categoryBreakdown}
            totalActivities={summary.stats.totalTasks + summary.stats.totalCheckboxes}
          />
        </>
      )}

      {/* Vue spécifique par catégorie */}
      {activeTab !== 'all' && (
        <Card>
          <CardHeader>
            <div className="flex items-center gap-3">
              <span className="text-2xl">{summary.categoryBreakdown[activeTab]?.icon}</span>
              <div>
                <h2 className="text-lg font-semibold">{activeTab}</h2>
                <p className="text-sm text-[var(--muted-foreground)]">
                  {summary.categoryBreakdown[activeTab]?.count} activités 
                  ({summary.categoryBreakdown[activeTab]?.percentage.toFixed(1)}% de votre temps)
                </p>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            {/* Métriques spécifiques à la catégorie */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
              <div className="bg-[var(--card)] p-4 rounded-lg border border-[var(--border)] text-center">
                <div className="text-2xl font-bold text-[var(--primary)]">
                  {filteredActivities.length}
                </div>
                <div className="text-sm text-[var(--muted-foreground)]">Total activités</div>
              </div>
              
              <div className="bg-[var(--card)] p-4 rounded-lg border border-[var(--border)] text-center">
                <div className="text-2xl font-bold text-[var(--success)]">
                  {filteredActivities.filter(a => a.completed).length}
                </div>
                <div className="text-sm text-[var(--muted-foreground)]">Complétées</div>
              </div>
              
              <div className="bg-[var(--card)] p-4 rounded-lg border border-[var(--border)] text-center">
                <div className="text-2xl font-bold text-[var(--accent)]">
                  {filteredActivities.length > 0 
                    ? Math.round((filteredActivities.filter(a => a.completed).length / filteredActivities.length) * 100)
                    : 0}%
                </div>
                <div className="text-sm text-[var(--muted-foreground)]">Taux completion</div>
              </div>
              
              <div className="bg-[var(--card)] p-4 rounded-lg border border-[var(--border)] text-center">
                <div className="text-2xl font-bold" style={{ color: summary.categoryBreakdown[activeTab]?.color }}>
                  {summary.categoryBreakdown[activeTab]?.percentage.toFixed(1)}%
                </div>
                <div className="text-sm text-[var(--muted-foreground)]">Du temps total</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Contenu commun à tous les onglets */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold">
                {activeTab === 'all' ? '📅 Résumé de la semaine' : `${summary.categoryBreakdown[activeTab]?.icon} Activités ${activeTab}`}
              </h2>
              <p className="text-sm text-[var(--muted-foreground)]">
                Du {formatDate(summary.period.start)} au {formatDate(summary.period.end)}
                {activeTab !== 'all' && ` • ${filteredActivities.length} activités`}
              </p>
            </div>
            <div className="flex gap-2">
              <Button 
                onClick={handleExportPDF} 
                variant="secondary" 
                size="sm"
                disabled={isExportingPDF}
              >
                {isExportingPDF ? '📄' : '📄'} {isExportingPDF ? 'Génération...' : 'Export PDF'}
              </Button>
              <Button 
                onClick={handleRefresh} 
                variant="secondary" 
                size="sm"
                disabled={isRefreshing}
              >
                {isRefreshing ? '🔄' : '🔄'} {isRefreshing ? 'Actualisation...' : 'Actualiser'}
              </Button>
            </div>
          </div>
        </CardHeader>

      <CardContent className="space-y-6">
        {/* Statistiques globales ou spécifiques à la catégorie */}
        {activeTab === 'all' ? (
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-blue-50 rounded-lg p-4 text-center">
              <div className="text-2xl font-bold text-blue-600">
                {summary.stats.completedCheckboxes}
              </div>
              <div className="text-sm text-blue-600">Daily items</div>
              <div className="text-xs text-[var(--muted-foreground)]">
                sur {summary.stats.totalCheckboxes} ({summary.stats.checkboxCompletionRate.toFixed(0)}%)
              </div>
            </div>

            <div className="bg-green-50 rounded-lg p-4 text-center">
              <div className="text-2xl font-bold text-green-600">
                {summary.stats.completedTasks}
              </div>
              <div className="text-sm text-green-600">Tâches</div>
              <div className="text-xs text-[var(--muted-foreground)]">
                sur {summary.stats.totalTasks} ({summary.stats.taskCompletionRate.toFixed(0)}%)
              </div>
            </div>

            <div className="bg-purple-50 rounded-lg p-4 text-center">
              <div className="text-2xl font-bold text-purple-600">
                {summary.stats.completedCheckboxes + summary.stats.completedTasks}
              </div>
              <div className="text-sm text-purple-600">Total complété</div>
              <div className="text-xs text-[var(--muted-foreground)]">
                sur {summary.stats.totalCheckboxes + summary.stats.totalTasks}
              </div>
            </div>

            <div className="bg-orange-50 rounded-lg p-4 text-center">
              <div className="text-lg font-bold text-orange-600">
                {summary.stats.mostProductiveDay}
              </div>
              <div className="text-sm text-orange-600">Jour le plus productif</div>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-blue-50 rounded-lg p-4 text-center">
              <div className="text-2xl font-bold text-blue-600">
                {filteredActivities.length}
              </div>
              <div className="text-sm text-blue-600">Activités {activeTab}</div>
            </div>

            <div className="bg-green-50 rounded-lg p-4 text-center">
              <div className="text-2xl font-bold text-green-600">
                {filteredActivities.filter(a => a.completed).length}
              </div>
              <div className="text-sm text-green-600">Complétées</div>
            </div>

            <div className="bg-purple-50 rounded-lg p-4 text-center">
              <div className="text-2xl font-bold text-purple-600">
                {filteredActivities.length > 0 
                  ? Math.round((filteredActivities.filter(a => a.completed).length / filteredActivities.length) * 100)
                  : 0}%
              </div>
              <div className="text-sm text-purple-600">Taux de réussite</div>
            </div>

            <div className="bg-orange-50 rounded-lg p-4 text-center">
              <div className="text-2xl font-bold text-orange-600">
                {summary.categoryBreakdown[activeTab]?.percentage.toFixed(1)}%
              </div>
              <div className="text-sm text-orange-600">Du temps total</div>
            </div>
          </div>
        )}

        {/* Breakdown par jour */}
        <div>
          <h3 className="font-medium mb-3">
            📊 Répartition par jour
            {activeTab !== 'all' && <span className="text-sm font-normal text-[var(--muted-foreground)]"> - {activeTab}</span>}
          </h3>
          <div className="grid grid-cols-7 gap-2 mb-4">
            {summary.stats.dailyBreakdown.map((day) => {
              // Pour chaque jour, calculer les activités de la catégorie sélectionnée
              const dayActivitiesAll = summary.activities.filter(a => a.dayName === day.dayName);
              const dayActivitiesFiltered = activeTab === 'all' 
                ? dayActivitiesAll 
                : dayActivitiesAll.filter(activity => getActivityCategory(activity) === activeTab);
              
              const completedCount = dayActivitiesFiltered.filter(a => a.completed).length;
              const totalCount = dayActivitiesFiltered.length;

              return (
                <button
                  key={day.date}
                  onClick={() => setSelectedDay(selectedDay === day.dayName ? null : day.dayName)}
                  className={`p-2 rounded-lg text-center transition-colors ${
                    selectedDay === day.dayName
                      ? 'bg-blue-100 border-2 border-blue-300'
                      : 'bg-[var(--muted)] hover:bg-[var(--muted)]/80'
                  }`}
                >
                  <div className="text-xs font-medium">
                    {day.dayName.slice(0, 3)}
                  </div>
                  <div className="text-sm font-bold">
                    {activeTab === 'all' ? (day.completedCheckboxes + day.completedTasks) : completedCount}
                  </div>
                  <div className="text-xs text-[var(--muted-foreground)]">
                    /{activeTab === 'all' ? (day.checkboxes + day.tasks) : totalCount}
                  </div>
                </button>
              );
            })}
          </div>
          {selectedDay && (
            <div className="text-sm text-[var(--muted-foreground)] mb-4">
              📍 Filtré sur: <strong>{selectedDay}</strong>
              {activeTab !== 'all' && <span> • Catégorie: <strong>{activeTab}</strong></span>}
              <button 
                onClick={() => setSelectedDay(null)}
                className="ml-2 text-blue-600 hover:underline"
              >
                (voir tout)
              </button>
            </div>
          )}
        </div>

        {/* Timeline des activités */}
        <div>
          <h3 className="font-medium mb-3">
            🕒 Timeline des activités {activeTab !== 'all' && `- ${activeTab}`}
            <span className="text-sm font-normal text-[var(--muted-foreground)]">
              ({filteredActivities.length} items{activeTab !== 'all' && ` de la catégorie ${activeTab}`})
            </span>
          </h3>
          
          {filteredActivities.length === 0 ? (
            <div className="text-center py-8 text-[var(--muted-foreground)]">
              {selectedDay ? 'Aucune activité ce jour-là' : 'Aucune activité cette semaine'}
            </div>
          ) : (
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {filteredActivities.map((activity) => (
                <div
                  key={activity.id}
                  className={`flex items-center gap-3 p-3 rounded-lg border transition-colors ${
                    activity.completed 
                      ? 'bg-green-50 border-green-200' 
                      : 'bg-[var(--card)] border-[var(--border)]'
                  }`}
                >
                  <span className="text-lg flex-shrink-0">
                    {getActivityIcon(activity)}
                  </span>
                  
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className={`text-sm ${activity.completed ? 'line-through text-[var(--muted-foreground)]' : ''}`}>
                        {activity.title}
                      </span>
                      <Badge className="text-xs bg-[var(--muted)] text-[var(--muted-foreground)]">
                        {getActivityTypeLabel(activity.type)}
                      </Badge>
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      {activity.dayName} • {new Date(activity.createdAt).toLocaleDateString('fr-FR')}
                      {activity.completedAt && (
                        <span> • Complété le {new Date(activity.completedAt).toLocaleDateString('fr-FR')}</span>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
    </div>
  );
}
