'use client';

import { useState } from 'react';
import { WeeklySummary, WeeklyActivity } from '@/services/weekly-summary';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';

interface WeeklySummaryClientProps {
  initialSummary: WeeklySummary;
}

export default function WeeklySummaryClient({ initialSummary }: WeeklySummaryClientProps) {
  const [summary] = useState<WeeklySummary>(initialSummary);
  const [selectedDay, setSelectedDay] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);

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

  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';
  };

  const filteredActivities = selectedDay 
    ? summary.activities.filter(a => a.dayName === selectedDay)
    : summary.activities;

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold">📅 Résumé de la semaine</h2>
            <p className="text-sm text-[var(--muted-foreground)]">
              Du {formatDate(summary.period.start)} au {formatDate(summary.period.end)}
            </p>
          </div>
          <Button 
            onClick={handleRefresh} 
            variant="secondary" 
            size="sm"
            disabled={isRefreshing}
          >
            {isRefreshing ? '🔄' : '🔄'} {isRefreshing ? 'Actualisation...' : 'Actualiser'}
          </Button>
        </div>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* Statistiques globales */}
        <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>

        {/* Breakdown par jour */}
        <div>
          <h3 className="font-medium mb-3">📊 Répartition par jour</h3>
          <div className="grid grid-cols-7 gap-2 mb-4">
            {summary.stats.dailyBreakdown.map((day) => (
              <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">
                  {day.completedCheckboxes + day.completedTasks}
                </div>
                <div className="text-xs text-[var(--muted-foreground)]">
                  /{day.checkboxes + day.tasks}
                </div>
              </button>
            ))}
          </div>
          {selectedDay && (
            <div className="text-sm text-[var(--muted-foreground)] mb-4">
              📍 Filtré sur: <strong>{selectedDay}</strong>
              <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 
            <span className="text-sm font-normal text-[var(--muted-foreground)]">
              ({filteredActivities.length} items)
            </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>
  );
}
