'use client';

import { useState, useMemo } from 'react';
import { ManagerSummary } from '@/services/analytics/manager-summary';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Tabs, TabItem } from '@/components/ui/Tabs';
import { TaskCard } from '@/components/ui/TaskCard';
import { FilterChip } from '@/components/ui/FilterChip';
import { useTasksContext } from '@/contexts/TasksContext';
import { MetricsTab } from './MetricsTab';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';
import { Tag } from '@/lib/types';
import { Emoji } from '@/components/ui/Emoji';

interface ManagerWeeklySummaryProps {
  initialSummary: ManagerSummary;
}

export default function ManagerWeeklySummary({
  initialSummary,
}: ManagerWeeklySummaryProps) {
  const [summary] = useState<ManagerSummary>(initialSummary);
  const [activeView, setActiveView] = useState<'narrative' | 'metrics'>(
    'narrative'
  );
  const [selectedAccomplishmentTags, setSelectedAccomplishmentTags] = useState<
    string[]
  >([]);
  const [selectedChallengeTags, setSelectedChallengeTags] = useState<string[]>(
    []
  );
  const { tags: availableTags } = useTasksContext();

  const handleTabChange = (tabId: string) => {
    setActiveView(tabId as 'narrative' | 'metrics');
  };

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

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

  // Calculer les compteurs pour chaque tag basés uniquement sur les accomplishments
  const accomplishmentTagCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    availableTags.forEach((tag) => {
      counts[tag.name] = summary.keyAccomplishments.filter((a) =>
        a.tags.includes(tag.name)
      ).length;
    });
    return counts;
  }, [availableTags, summary.keyAccomplishments]);

  // Calculer les compteurs pour chaque tag basés uniquement sur les challenges
  const challengeTagCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    availableTags.forEach((tag) => {
      counts[tag.name] = summary.upcomingChallenges.filter((c) =>
        c.tags.includes(tag.name)
      ).length;
    });
    return counts;
  }, [availableTags, summary.upcomingChallenges]);

  // Trier les tags pour les accomplishments par nombre d'utilisation (décroissant)
  const sortedAccomplishmentTags = useMemo(() => {
    return [...availableTags]
      .filter((tag) => (accomplishmentTagCounts[tag.name] || 0) > 0)
      .sort((a, b) => {
        const countA = accomplishmentTagCounts[a.name] || 0;
        const countB = accomplishmentTagCounts[b.name] || 0;
        return countB - countA;
      });
  }, [availableTags, accomplishmentTagCounts]);

  // Trier les tags pour les challenges par nombre d'utilisation (décroissant)
  const sortedChallengeTags = useMemo(() => {
    return [...availableTags]
      .filter((tag) => (challengeTagCounts[tag.name] || 0) > 0)
      .sort((a, b) => {
        const countA = challengeTagCounts[a.name] || 0;
        const countB = challengeTagCounts[b.name] || 0;
        return countB - countA;
      });
  }, [availableTags, challengeTagCounts]);

  // Filtrer les accomplishments selon les tags sélectionnés
  const filteredAccomplishments = useMemo(() => {
    if (selectedAccomplishmentTags.length === 0) {
      return summary.keyAccomplishments;
    }
    return summary.keyAccomplishments.filter((accomplishment) =>
      selectedAccomplishmentTags.some((tag) =>
        accomplishment.tags.includes(tag)
      )
    );
  }, [summary.keyAccomplishments, selectedAccomplishmentTags]);

  // Filtrer les challenges selon les tags sélectionnés
  const filteredChallenges = useMemo(() => {
    if (selectedChallengeTags.length === 0) {
      return summary.upcomingChallenges;
    }
    return summary.upcomingChallenges.filter((challenge) =>
      selectedChallengeTags.some((tag) => challenge.tags.includes(tag))
    );
  }, [summary.upcomingChallenges, selectedChallengeTags]);

  const handleAccomplishmentTagToggle = (tagName: string) => {
    setSelectedAccomplishmentTags((prev) =>
      prev.includes(tagName)
        ? prev.filter((t) => t !== tagName)
        : [...prev, tagName]
    );
  };

  const handleChallengeTagToggle = (tagName: string) => {
    setSelectedChallengeTags((prev) =>
      prev.includes(tagName)
        ? prev.filter((t) => t !== tagName)
        : [...prev, tagName]
    );
  };

  const handleClearAccomplishmentFilters = () => {
    setSelectedAccomplishmentTags([]);
  };

  const handleClearChallengeFilters = () => {
    setSelectedChallengeTags([]);
  };

  // Configuration des onglets
  const tabItems: TabItem[] = [
    { id: 'narrative', label: 'Vue Executive', icon: '📝' },
    { id: 'metrics', label: 'Métriques', icon: '📊' },
  ];

  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)]">
            <Emoji emoji="👔" /> Weekly
          </h1>
          <p className="text-[var(--muted-foreground)]">{formatPeriod()}</p>
        </div>
        {activeView !== 'metrics' && (
          <Button onClick={handleRefresh} variant="secondary" size="sm">
            <Emoji emoji="🔄" />
            &nbsp;Actualiser
          </Button>
        )}
      </div>

      {/* Navigation des vues */}
      <Tabs
        items={tabItems}
        activeTab={activeView}
        onTabChange={handleTabChange}
      />

      {/* Vue Executive / Narrative */}
      {activeView === 'narrative' && (
        <div className="space-y-6">
          {/* Section principale : Résumé + Métriques côte à côte */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Résumé narratif */}
            <Card variant="elevated">
              <CardHeader>
                <h2 className="text-lg font-semibold flex items-center gap-2">
                  <Emoji emoji="📊" /> Résumé de la semaine
                </h2>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="outline-card-blue p-4">
                  <h3 className="font-medium mb-2">
                    <Emoji emoji="🎯" /> Points clés accomplis
                  </h3>
                  <p className="text-sm text-[var(--muted-foreground)]">
                    {summary.narrative.weekHighlight}
                  </p>
                </div>

                <div className="outline-card-orange p-4">
                  <h3 className="font-medium mb-2">
                    <Emoji emoji="⚡" /> Défis traités
                  </h3>
                  <p className="text-sm text-[var(--muted-foreground)]">
                    {summary.narrative.mainChallenges}
                  </p>
                </div>

                <div className="outline-card-green p-4">
                  <h3 className="font-medium mb-2">
                    <Emoji emoji="🔮" /> Focus 7 prochains jours
                  </h3>
                  <p className="text-sm text-[var(--muted-foreground)]">
                    {summary.narrative.nextWeekFocus}
                  </p>
                </div>
              </CardContent>
            </Card>

            {/* Métriques rapides */}
            <Card variant="elevated">
              <CardHeader>
                <h2 className="text-lg font-semibold">
                  <Emoji emoji="📈" /> Métriques en bref
                </h2>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-4">
                  <div className="outline-metric-blue">
                    <div className="text-2xl font-bold mb-1">
                      {summary.metrics.totalTasksCompleted}
                    </div>
                    <div className="text-xs font-medium mb-1">
                      Tâches complétées
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      dont {summary.metrics.highPriorityTasksCompleted} priorité
                      haute
                    </div>
                  </div>

                  <div className="outline-metric-green">
                    <div className="text-2xl font-bold mb-1">
                      {summary.metrics.totalCheckboxesCompleted}
                    </div>
                    <div className="text-xs font-medium mb-1">
                      Todos complétés
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      dont {summary.metrics.meetingCheckboxesCompleted} meetings
                    </div>
                  </div>

                  <div className="outline-metric-orange">
                    <div className="text-2xl font-bold mb-1">
                      {
                        summary.keyAccomplishments.filter(
                          (a) => a.impact === 'high'
                        ).length
                      }
                    </div>
                    <div className="text-xs font-medium mb-1">
                      Items à fort impact
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      / {summary.keyAccomplishments.length} accomplissements
                    </div>
                  </div>

                  <div className="outline-metric-gray">
                    <div className="text-2xl font-bold mb-1">
                      {
                        summary.upcomingChallenges.filter(
                          (c) => c.priority === 'high'
                        ).length
                      }
                    </div>
                    <div className="text-xs font-medium mb-1">
                      Priorités critiques
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      / {summary.upcomingChallenges.length} enjeux
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Accomplissements détaillés */}
          <Card variant="elevated">
            <CardHeader
              className="pb-4"
              style={{
                borderBottom: '1px solid',
                borderBottomColor:
                  'color-mix(in srgb, var(--success) 10%, var(--border))',
              }}
            >
              <h2
                className="text-lg font-semibold flex items-center gap-2"
                style={{ color: 'var(--success)' }}
              >
                <Emoji emoji="🏆" /> Accomplissements
              </h2>
              <p className="text-sm text-[var(--muted-foreground)] mt-1">
                {filteredAccomplishments.length} accomplissement
                {filteredAccomplishments.length > 1 ? 's' : ''} affiché
                {selectedAccomplishmentTags.length > 0 && (
                  <span className="ml-2">
                    (sur {summary.keyAccomplishments.length} total)
                  </span>
                )}
                {selectedAccomplishmentTags.length === 0 && (
                  <>
                    {' '}
                    • {summary.metrics.totalTasksCompleted} tâches •{' '}
                    {summary.metrics.totalCheckboxesCompleted} todos complétés
                  </>
                )}
              </p>
            </CardHeader>
            {/* Filtres par tags pour les accomplishments */}
            {sortedAccomplishmentTags.length > 0 && (
              <CardContent className="pb-4 border-b border-[var(--border)]">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-xs font-semibold flex items-center gap-2 text-[var(--muted-foreground)]">
                    <Emoji emoji="🏷️" /> Filtres
                  </h3>
                  {selectedAccomplishmentTags.length > 0 && (
                    <Button
                      onClick={handleClearAccomplishmentFilters}
                      variant="ghost"
                      size="sm"
                      className="text-xs h-6"
                    >
                      Réinitialiser ({selectedAccomplishmentTags.length})
                    </Button>
                  )}
                </div>
                <div className="flex flex-wrap gap-2">
                  {sortedAccomplishmentTags.map((tag) => (
                    <FilterChip
                      key={tag.id}
                      onClick={() => handleAccomplishmentTagToggle(tag.name)}
                      variant={
                        selectedAccomplishmentTags.includes(tag.name)
                          ? 'selected'
                          : 'tag'
                      }
                      color={tag.color}
                      count={accomplishmentTagCounts[tag.name]}
                    >
                      {tag.name}
                    </FilterChip>
                  ))}
                </div>
              </CardContent>
            )}
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {filteredAccomplishments.length === 0 ? (
                  <div className="col-span-3 text-center py-8 text-[var(--muted-foreground)]">
                    <div className="text-4xl mb-4">
                      <Emoji emoji="📭" />
                    </div>
                    <p className="text-lg mb-2">
                      Aucun accomplissement significatif trouvé cette semaine.
                    </p>
                    <p className="text-sm">
                      Ajoutez des tâches avec priorité haute/medium ou des
                      meetings.
                    </p>
                  </div>
                ) : (
                  filteredAccomplishments.map((accomplishment) => (
                    <TaskCard
                      key={accomplishment.id}
                      variant="detailed"
                      title={accomplishment.title}
                      description={accomplishment.description}
                      tags={accomplishment.tags}
                      priority={
                        accomplishment.impact === 'high'
                          ? 'high'
                          : accomplishment.impact === 'medium'
                            ? 'medium'
                            : 'low'
                      }
                      status="done"
                      completedAt={accomplishment.completedAt}
                      todosCount={accomplishment.todosCount}
                      availableTags={availableTags as Tag[]}
                      source="manual"
                      style={{ opacity: 1 }}
                    />
                  ))
                )}
              </div>
            </CardContent>
          </Card>

          {/* Enjeux à venir détaillés */}
          <Card variant="elevated">
            <CardHeader
              className="pb-4"
              style={{
                borderBottom: '1px solid',
                borderBottomColor:
                  'color-mix(in srgb, var(--destructive) 10%, var(--border))',
              }}
            >
              <h2
                className="text-lg font-semibold flex items-center gap-2"
                style={{ color: 'var(--destructive)' }}
              >
                <Emoji emoji="🎯" /> Enjeux à venir
              </h2>
              <p className="text-sm text-[var(--muted-foreground)] mt-1">
                {filteredChallenges.length} défi
                {filteredChallenges.length > 1 ? 's' : ''} affiché
                {selectedChallengeTags.length > 0 && (
                  <span className="ml-2">
                    (sur {summary.upcomingChallenges.length} total)
                  </span>
                )}
                {selectedChallengeTags.length === 0 && (
                  <>
                    {' '}
                    •{' '}
                    {
                      summary.upcomingChallenges.filter(
                        (c) => c.priority === 'high'
                      ).length
                    }{' '}
                    priorité haute •{' '}
                    {
                      summary.upcomingChallenges.filter(
                        (c) => c.blockers.length > 0
                      ).length
                    }{' '}
                    avec blockers
                  </>
                )}
              </p>
            </CardHeader>
            {/* Filtres par tags pour les challenges */}
            {sortedChallengeTags.length > 0 && (
              <CardContent className="pb-4 border-b border-[var(--border)]">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-xs font-semibold flex items-center gap-2 text-[var(--muted-foreground)]">
                    <Emoji emoji="🏷️" /> Filtres
                  </h3>
                  {selectedChallengeTags.length > 0 && (
                    <Button
                      onClick={handleClearChallengeFilters}
                      variant="ghost"
                      size="sm"
                      className="text-xs h-6"
                    >
                      Réinitialiser ({selectedChallengeTags.length})
                    </Button>
                  )}
                </div>
                <div className="flex flex-wrap gap-2">
                  {sortedChallengeTags.map((tag) => (
                    <FilterChip
                      key={tag.id}
                      onClick={() => handleChallengeTagToggle(tag.name)}
                      variant={
                        selectedChallengeTags.includes(tag.name)
                          ? 'selected'
                          : 'tag'
                      }
                      color={tag.color}
                      count={challengeTagCounts[tag.name]}
                    >
                      {tag.name}
                    </FilterChip>
                  ))}
                </div>
              </CardContent>
            )}
            <CardContent
              className={sortedChallengeTags.length > 0 ? 'pt-4' : ''}
            >
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {filteredChallenges.length === 0 ? (
                  <div className="col-span-3 text-center py-8 text-[var(--muted-foreground)]">
                    <div className="text-4xl mb-4">
                      <Emoji emoji="🎯" />
                    </div>
                    <p className="text-lg mb-2">
                      Aucun enjeu prioritaire trouvé.
                    </p>
                    <p className="text-sm">
                      Ajoutez des tâches non complétées avec priorité
                      haute/medium.
                    </p>
                  </div>
                ) : (
                  filteredChallenges.map((challenge) => (
                    <TaskCard
                      key={challenge.id}
                      variant="detailed"
                      title={challenge.title}
                      description={challenge.description}
                      tags={challenge.tags}
                      priority={challenge.priority}
                      status="todo"
                      dueDate={challenge.deadline}
                      todosCount={challenge.todosCount}
                      availableTags={availableTags as Tag[]}
                      source="manual"
                    />
                  ))
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Vue Métriques */}
      {activeView === 'metrics' && <MetricsTab />}
    </div>
  );
}
