'use client';

import { useState } from 'react';
import { ManagerSummary } from '@/services/manager-summary';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { TagDisplay } from '@/components/ui/TagDisplay';
import { getPriorityConfig } from '@/lib/status-config';
import { useTasksContext } from '@/contexts/TasksContext';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';

interface ManagerWeeklySummaryProps {
  initialSummary: ManagerSummary;
}

export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySummaryProps) {
  const [summary] = useState<ManagerSummary>(initialSummary);
  const [activeView, setActiveView] = useState<'narrative' | 'accomplishments' | 'challenges'>('narrative');
  const { tags: availableTags } = useTasksContext();

  const handleRefresh = () => {
    // SSR - refresh via page reload
    window.location.reload();
  };


  const formatPeriod = () => {
    return `Semaine du ${format(summary.period.start, 'dd MMM', { locale: fr })} au ${format(summary.period.end, 'dd MMM yyyy', { locale: fr })}`;
  };

  const getPriorityBadgeStyle = (priority: 'low' | 'medium' | 'high') => {
    const config = getPriorityConfig(priority);
    const baseClasses = 'text-xs px-2 py-0.5 rounded font-medium';
    
    switch (config.color) {
      case 'blue':
        return `${baseClasses} bg-blue-100 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400`;
      case 'yellow':
        return `${baseClasses} bg-yellow-100 dark:bg-yellow-900/20 text-yellow-600 dark:text-yellow-400`;
      case 'purple':
        return `${baseClasses} bg-purple-100 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400`;
      case 'red':
        return `${baseClasses} bg-red-100 dark:bg-red-900/20 text-red-600 dark:text-red-400`;
      default:
        return `${baseClasses} bg-gray-100 dark:bg-gray-900/20 text-gray-600 dark:text-gray-400`;
    }
  };


  return (
    <div className="space-y-6">
      {/* Header avec navigation */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-[var(--foreground)]">👔 Résumé Manager</h1>
          <p className="text-[var(--muted-foreground)]">{formatPeriod()}</p>
        </div>
        <Button 
          onClick={handleRefresh} 
          variant="secondary" 
          size="sm"
        >
          🔄 Actualiser
        </Button>
      </div>

      {/* Navigation des vues */}
      <div className="border-b border-[var(--border)]">
        <nav className="flex space-x-8">
          <button
            onClick={() => setActiveView('narrative')}
            className={`py-3 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeView === 'narrative'
                ? 'border-[var(--primary)] text-[var(--primary)]'
                : 'border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)]'
            }`}
          >
            📝 Vue Executive
          </button>
          <button
            onClick={() => setActiveView('accomplishments')}
            className={`py-3 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeView === 'accomplishments'
                ? 'border-[var(--primary)] text-[var(--primary)]'
                : 'border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)]'
            }`}
          >
            ✅ Accomplissements ({summary.keyAccomplishments.length})
          </button>
          <button
            onClick={() => setActiveView('challenges')}
            className={`py-3 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeView === 'challenges'
                ? 'border-[var(--primary)] text-[var(--primary)]'
                : 'border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)]'
            }`}
          >
            🎯 Enjeux à venir ({summary.upcomingChallenges.length})
          </button>
        </nav>
      </div>

      {/* Vue Executive / Narrative */}
      {activeView === 'narrative' && (
        <div className="space-y-6">
          {/* Résumé narratif */}
          <Card>
            <CardHeader>
              <h2 className="text-lg font-semibold flex items-center gap-2">
                📊 Résumé de la semaine
              </h2>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="bg-blue-50 p-4 rounded-lg border-l-4 border-blue-400">
                <h3 className="font-medium text-blue-900 mb-2">🎯 Points clés accomplis</h3>
                <p className="text-blue-800">{summary.narrative.weekHighlight}</p>
              </div>
              
              <div className="bg-yellow-50 p-4 rounded-lg border-l-4 border-yellow-400">
                <h3 className="font-medium text-yellow-900 mb-2">⚡ Défis traités</h3>
                <p className="text-yellow-800">{summary.narrative.mainChallenges}</p>
              </div>
              
              <div className="bg-green-50 p-4 rounded-lg border-l-4 border-green-400">
                <h3 className="font-medium text-green-900 mb-2">🔮 Focus semaine prochaine</h3>
                <p className="text-green-800">{summary.narrative.nextWeekFocus}</p>
              </div>
            </CardContent>
          </Card>

          {/* Métriques rapides */}
          <Card>
            <CardHeader>
              <h2 className="text-lg font-semibold">📈 Métriques en bref</h2>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                <div className="text-center p-4 bg-blue-50 rounded-lg">
                  <div className="text-2xl font-bold text-blue-600">
                    {summary.metrics.totalTasksCompleted}
                  </div>
                  <div className="text-sm text-blue-600">Tâches complétées</div>
                  <div className="text-xs text-blue-500">
                    dont {summary.metrics.highPriorityTasksCompleted} priorité haute
                  </div>
                </div>
                
                <div className="text-center p-4 bg-green-50 rounded-lg">
                  <div className="text-2xl font-bold text-green-600">
                    {summary.metrics.totalCheckboxesCompleted}
                  </div>
                  <div className="text-sm text-green-600">Todos complétés</div>
                  <div className="text-xs text-green-500">
                    dont {summary.metrics.meetingCheckboxesCompleted} meetings
                  </div>
                </div>
                
                <div className="text-center p-4 bg-purple-50 rounded-lg">
                  <div className="text-2xl font-bold text-purple-600">
                    {summary.keyAccomplishments.filter(a => a.impact === 'high').length}
                  </div>
                  <div className="text-sm text-purple-600">Items à fort impact</div>
                  <div className="text-xs text-purple-500">
                    / {summary.keyAccomplishments.length} accomplissements
                  </div>
                </div>
                
                <div className="text-center p-4 bg-orange-50 rounded-lg">
                  <div className="text-2xl font-bold text-orange-600">
                    {summary.upcomingChallenges.filter(c => c.priority === 'high').length}
                  </div>
                  <div className="text-sm text-orange-600">Priorités critiques</div>
                  <div className="text-xs text-orange-500">
                    / {summary.upcomingChallenges.length} enjeux
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Top accomplissements */}
          <Card>
            <CardHeader>
              <h2 className="text-lg font-semibold">🏆 Top accomplissements</h2>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                {summary.keyAccomplishments.length === 0 ? (
                  <div className="col-span-3 text-center py-8 text-[var(--muted-foreground)]">
                    <p>Aucun accomplissement significatif trouvé cette semaine.</p>
                    <p className="text-sm mt-2">Ajoutez des tâches avec priorité haute/medium ou des meetings.</p>
                  </div>
                  ) : (
                    summary.keyAccomplishments.slice(0, 6).map((accomplishment, index) => (
                      <div 
                        key={accomplishment.id} 
                        className="relative bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 hover:bg-green-50/50 dark:hover:bg-green-950/20 transition-all duration-200 group"
                      >
                        {/* Barre colorée gauche */}
                        <div className="absolute left-0 top-0 bottom-0 w-1 bg-green-500 rounded-l-lg"></div>
                        
                        {/* Header compact */}
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <span className="w-5 h-5 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-full text-xs font-bold flex items-center justify-center">
                              #{index + 1}
                            </span>
                            <span className={getPriorityBadgeStyle(accomplishment.impact)}>
                              {getPriorityConfig(accomplishment.impact).label}
                            </span>
                          </div>
                          <span className="text-xs text-[var(--muted-foreground)]">
                            {format(accomplishment.completedAt, 'dd/MM', { locale: fr })}
                          </span>
                        </div>
                        
                        {/* Titre */}
                        <h4 className="font-semibold text-sm text-[var(--foreground)] mb-2 line-clamp-2">
                          {accomplishment.title}
                        </h4>
                        
                        {/* Tags */}
                        {accomplishment.tags && accomplishment.tags.length > 0 && (
                          <div className="mb-2">
                            <TagDisplay 
                              tags={accomplishment.tags} 
                              availableTags={availableTags}
                              size="sm"
                              maxTags={2}
                            />
                          </div>
                        )}
                        
                        {/* Description si disponible */}
                        {accomplishment.description && (
                          <p className="text-xs text-[var(--muted-foreground)] line-clamp-2 leading-relaxed mb-2">
                            {accomplishment.description}
                          </p>
                        )}
                        
                        {/* Count de todos */}
                        {accomplishment.todosCount > 0 && (
                          <div className="flex items-center gap-1 text-xs text-[var(--muted-foreground)]">
                            <span>📋</span>
                            <span>{accomplishment.todosCount} todo{accomplishment.todosCount > 1 ? 's' : ''}</span>
                          </div>
                        )}
                      </div>
                    ))
                  )}
              </div>
            </CardContent>
          </Card>

          {/* Top challenges */}
          <Card>
            <CardHeader>
              <h2 className="text-lg font-semibold">🎯 Top enjeux à venir</h2>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                {summary.upcomingChallenges.length === 0 ? (
                  <div className="col-span-3 text-center py-8 text-[var(--muted-foreground)]">
                    <p>Aucun enjeu prioritaire trouvé.</p>
                    <p className="text-sm mt-2">Ajoutez des tâches non complétées avec priorité haute/medium.</p>
                  </div>
                  ) : (
                    summary.upcomingChallenges.slice(0, 6).map((challenge, index) => (
                      <div 
                        key={challenge.id} 
                        className="relative bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 hover:bg-orange-50/50 dark:hover:bg-orange-950/20 transition-all duration-200 group"
                      >
                        {/* Barre colorée gauche */}
                        <div className="absolute left-0 top-0 bottom-0 w-1 bg-orange-500 rounded-l-lg"></div>
                        
                        {/* Header compact */}
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <span className="w-5 h-5 bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300 rounded-full text-xs font-bold flex items-center justify-center">
                              #{index + 1}
                            </span>
                            <span className={getPriorityBadgeStyle(challenge.priority)}>
                              {getPriorityConfig(challenge.priority).label}
                            </span>
                          </div>
                          {challenge.deadline && (
                            <span className="text-xs text-[var(--muted-foreground)]">
                              {format(challenge.deadline, 'dd/MM', { locale: fr })}
                            </span>
                          )}
                        </div>
                      
                      {/* Titre */}
                      <h4 className="font-semibold text-sm text-[var(--foreground)] mb-2 line-clamp-2">
                        {challenge.title}
                      </h4>
                      
                      {/* Tags */}
                      {challenge.tags && challenge.tags.length > 0 && (
                        <div className="mb-2">
                          <TagDisplay 
                            tags={challenge.tags} 
                            availableTags={availableTags}
                            size="sm"
                            maxTags={2}
                          />
                        </div>
                      )}
                      
                      {/* Description si disponible */}
                      {challenge.description && (
                        <p className="text-xs text-[var(--muted-foreground)] line-clamp-2 leading-relaxed mb-2">
                          {challenge.description}
                        </p>
                      )}
                      
                      {/* Count de todos */}
                      {challenge.todosCount > 0 && (
                        <div className="flex items-center gap-1 text-xs text-[var(--muted-foreground)]">
                          <span>📋</span>
                          <span>{challenge.todosCount} todo{challenge.todosCount > 1 ? 's' : ''}</span>
                        </div>
                      )}
                    </div>
                  ))
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Vue détaillée des accomplissements */}
      {activeView === 'accomplishments' && (
        <Card>
          <CardHeader>
            <h2 className="text-lg font-semibold">✅ Accomplissements de la semaine</h2>
            <p className="text-sm text-[var(--muted-foreground)]">
              {summary.keyAccomplishments.length} accomplissements significatifs • {summary.metrics.totalTasksCompleted} tâches • {summary.metrics.totalCheckboxesCompleted} todos complétés
            </p>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {summary.keyAccomplishments.map((accomplishment, index) => (
                <div 
                  key={accomplishment.id} 
                  className="relative bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 hover:bg-green-50/50 dark:hover:bg-green-950/20 transition-all duration-200 group"
                >
                  {/* Barre colorée gauche */}
                  <div className="absolute left-0 top-0 bottom-0 w-1 bg-green-500 rounded-l-lg"></div>
                  
                  {/* Header compact */}
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <span className="w-5 h-5 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-full text-xs font-bold flex items-center justify-center">
                        #{index + 1}
                      </span>
                      <span className={getPriorityBadgeStyle(accomplishment.impact)}>
                        {getPriorityConfig(accomplishment.impact).label}
                      </span>
                    </div>
                    <span className="text-xs text-[var(--muted-foreground)]">
                      {format(accomplishment.completedAt, 'dd/MM', { locale: fr })}
                    </span>
                  </div>
                  
                  {/* Titre */}
                  <h4 className="font-semibold text-sm text-[var(--foreground)] mb-2 line-clamp-2">
                    {accomplishment.title}
                  </h4>
                  
                  {/* Tags */}
                  {accomplishment.tags && accomplishment.tags.length > 0 && (
                    <div className="mb-2">
                      <TagDisplay 
                        tags={accomplishment.tags} 
                        availableTags={availableTags}
                        size="sm"
                        maxTags={3}
                      />
                    </div>
                  )}
                  
                  {/* Description si disponible */}
                  {accomplishment.description && (
                    <p className="text-xs text-[var(--muted-foreground)] line-clamp-3 leading-relaxed mb-2">
                      {accomplishment.description}
                    </p>
                  )}
                  
                  {/* Count de todos */}
                  {accomplishment.todosCount > 0 && (
                    <div className="flex items-center gap-1 text-xs text-[var(--muted-foreground)]">
                      <span>📋</span>
                      <span>{accomplishment.todosCount} todo{accomplishment.todosCount > 1 ? 's' : ''}</span>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Vue détaillée des challenges */}
      {activeView === 'challenges' && (
        <Card>
          <CardHeader>
            <h2 className="text-lg font-semibold">🎯 Enjeux et défis à venir</h2>
            <p className="text-sm text-[var(--muted-foreground)]">
              {summary.upcomingChallenges.length} défis identifiés • {summary.upcomingChallenges.filter(c => c.priority === 'high').length} priorité haute • {summary.upcomingChallenges.filter(c => c.blockers.length > 0).length} avec blockers
            </p>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {summary.upcomingChallenges.map((challenge, index) => (
                <div 
                  key={challenge.id} 
                  className="relative bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 hover:bg-orange-50/50 dark:hover:bg-orange-950/20 transition-all duration-200 group"
                >
                  {/* Barre colorée gauche */}
                  <div className="absolute left-0 top-0 bottom-0 w-1 bg-orange-500 rounded-l-lg"></div>
                  
                  {/* Header compact */}
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <span className="w-5 h-5 bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300 rounded-full text-xs font-bold flex items-center justify-center">
                        #{index + 1}
                      </span>
                      <span className={getPriorityBadgeStyle(challenge.priority)}>
                        {getPriorityConfig(challenge.priority).label}
                      </span>
                    </div>
                    {challenge.deadline && (
                      <span className="text-xs text-[var(--muted-foreground)]">
                        {format(challenge.deadline, 'dd/MM', { locale: fr })}
                      </span>
                    )}
                  </div>
                  
                  {/* Titre */}
                  <h4 className="font-semibold text-sm text-[var(--foreground)] mb-2 line-clamp-2">
                    {challenge.title}
                  </h4>
                  
                  {/* Tags */}
                  {challenge.tags && challenge.tags.length > 0 && (
                    <div className="mb-2">
                      <TagDisplay 
                        tags={challenge.tags} 
                        availableTags={availableTags}
                        size="sm"
                        maxTags={3}
                      />
                    </div>
                  )}
                  
                  {/* Description si disponible */}
                  {challenge.description && (
                    <p className="text-xs text-[var(--muted-foreground)] line-clamp-3 leading-relaxed mb-2">
                      {challenge.description}
                    </p>
                  )}
                  
                  {/* Count de todos */}
                  {challenge.todosCount > 0 && (
                    <div className="flex items-center gap-1 text-xs text-[var(--muted-foreground)]">
                      <span>📋</span>
                      <span>{challenge.todosCount} todo{challenge.todosCount > 1 ? 's' : ''}</span>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
