'use client';

import { useState, useEffect } from 'react';
import React from 'react';
import { useDaily } from '@/hooks/useDaily';
import { DailyView, DailyCheckboxType, DailyCheckbox, Task } from '@/lib/types';
import { DeadlineMetrics } from '@/services/analytics/deadline-analytics';
import { Button } from '@/components/ui/Button';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { TaskCard } from '@/components/ui/TaskCard';
import { useTags } from '@/hooks/useTags';
import { Calendar } from '@/components/ui/Calendar';
import { AlertBanner, AlertItem } from '@/components/ui/AlertBanner';
import { DailySection } from '@/components/daily/DailySection';
import { PendingTasksSection } from '@/components/daily/PendingTasksSection';
import { dailyClient } from '@/clients/daily-client';
import { Header } from '@/components/ui/Header';
import {
  getPreviousWorkday,
  formatDateLong,
  isToday,
  generateDateTitle,
  formatDateForAPI,
} from '@/lib/date-utils';
import { useGlobalKeyboardShortcuts } from '@/hooks/useGlobalKeyboardShortcuts';
import { Emoji } from '@/components/ui/Emoji';

interface DailyPageClientProps {
  initialDailyView?: DailyView;
  initialDailyDates?: string[];
  initialDeadlineDates?: Record<string, string[]>; // Date -> Array de noms de tâches
  initialDate?: Date;
  initialDeadlineMetrics?: DeadlineMetrics | null;
  initialPendingTasks?: DailyCheckbox[];
}

export function DailyPageClient({
  initialDailyView,
  initialDailyDates = [],
  initialDeadlineDates = {},
  initialDate,
  initialDeadlineMetrics,
  initialPendingTasks = [],
}: DailyPageClientProps = {}) {
  const { tags: availableTags } = useTags();
  const {
    dailyView,
    loading,
    refreshing,
    error,
    saving,
    currentDate,
    addTodayCheckbox,
    addYesterdayCheckbox,
    toggleCheckbox,
    toggleAllToday,
    toggleAllYesterday,
    updateCheckbox,
    deleteCheckbox,
    reorderCheckboxes,
    goToPreviousDay,
    goToNextDay,
    goToToday,
    setDate,
    refreshDailySilent,
  } = useDaily(initialDate, initialDailyView);

  const [dailyDates, setDailyDates] = useState<string[]>(initialDailyDates);
  const [deadlineDates, setDeadlineDates] =
    useState<Record<string, string[]>>(initialDeadlineDates);
  const [deadlineTasks, setDeadlineTasks] = useState<Task[]>([]);
  const [loadingDeadlineTasks, setLoadingDeadlineTasks] = useState(false);
  const [pendingRefreshTrigger, setPendingRefreshTrigger] = useState(0);

  // Fonction pour rafraîchir la liste des dates avec des dailies
  const refreshDailyDates = async () => {
    try {
      const dates = await dailyClient.getDailyDates();
      setDailyDates(dates);
    } catch (error) {
      console.error('Erreur lors du refresh des dates:', error);
    }
  };

  // Charger les dates avec des dailies pour le calendrier (seulement si pas de données SSR)
  useEffect(() => {
    if (initialDailyDates.length === 0) {
      import('@/clients/daily-client')
        .then(({ dailyClient }) => {
          return dailyClient.getDailyDates();
        })
        .then(setDailyDates)
        .catch(console.error);
    }
  }, [initialDailyDates.length]);

  // Charger les dates de fin pour le calendrier (seulement si pas de données SSR)
  useEffect(() => {
    if (Object.keys(initialDeadlineDates).length === 0) {
      import('@/clients/daily-client')
        .then(({ dailyClient }) => {
          return dailyClient.getDeadlineDates();
        })
        .then(setDeadlineDates)
        .catch(console.error);
    }
  }, [initialDeadlineDates]);

  const handleAddTodayCheckbox = async (
    text: string,
    type: DailyCheckboxType
  ) => {
    await addTodayCheckbox(text, type);
    // Recharger aussi les dates pour le calendrier
    await refreshDailyDates();
    setPendingRefreshTrigger((prev) => prev + 1);
  };

  const handleAddYesterdayCheckbox = async (
    text: string,
    type: DailyCheckboxType
  ) => {
    await addYesterdayCheckbox(text, type);
    // Recharger aussi les dates pour le calendrier
    await refreshDailyDates();
    setPendingRefreshTrigger((prev) => prev + 1);
  };

  // Raccourcis clavier globaux pour la page Daily
  useGlobalKeyboardShortcuts({
    onNavigatePrevious: goToPreviousDay,
    onNavigateNext: goToNextDay,
    onGoToToday: goToToday,
  });

  const handleToggleCheckbox = async (checkboxId: string) => {
    await toggleCheckbox(checkboxId);
    setPendingRefreshTrigger((prev) => prev + 1);
  };

  const handleDeleteCheckbox = async (checkboxId: string) => {
    await deleteCheckbox(checkboxId);
    // Refresh dates après suppression pour mettre à jour le calendrier
    await refreshDailyDates();
    setPendingRefreshTrigger((prev) => prev + 1);
  };

  const handleUpdateCheckbox = async (
    checkboxId: string,
    text: string,
    type: DailyCheckboxType,
    taskId?: string,
    date?: Date
  ) => {
    await updateCheckbox(checkboxId, {
      text,
      type,
      taskId, // Permet la liaison tâche pour tous les types
      date, // Permet la modification de la date/heure
    });
    // Refresh dates après modification pour mettre à jour le calendrier si la date a changé
    if (date) {
      await refreshDailyDates();
    }
    setPendingRefreshTrigger((prev) => prev + 1);
  };

  const handleReorderCheckboxes = async (date: Date, checkboxIds: string[]) => {
    await reorderCheckboxes({ date, checkboxIds });
  };

  const getYesterdayDate = () => {
    return getPreviousWorkday(currentDate);
  };

  const getTodayDate = () => {
    return currentDate;
  };

  const handleDateSelect = (date: Date) => {
    setDate(date);
  };

  const formatCurrentDate = () => {
    return formatDateLong(currentDate);
  };

  // Charger les tâches complètes pour la date sélectionnée
  useEffect(() => {
    const loadDeadlineTasks = async () => {
      const dateKey = formatDateForAPI(currentDate);
      if (deadlineDates[dateKey] && deadlineDates[dateKey].length > 0) {
        setLoadingDeadlineTasks(true);
        try {
          const tasks = await dailyClient.getDeadlineTasksForDate(currentDate);
          setDeadlineTasks(tasks);
        } catch (error) {
          console.error('Erreur lors du chargement des tâches:', error);
          setDeadlineTasks([]);
        } finally {
          setLoadingDeadlineTasks(false);
        }
      } else {
        setDeadlineTasks([]);
      }
    };

    loadDeadlineTasks();
  }, [currentDate, deadlineDates]);

  const isTodayDate = () => {
    return isToday(currentDate);
  };

  const getTodayTitle = () => {
    const { emoji, text } = generateDateTitle(currentDate, '🎯');
    return (
      <>
        <Emoji emoji={emoji} /> {text}
      </>
    );
  };

  const getYesterdayTitle = () => {
    const yesterdayDate = getYesterdayDate();
    const { emoji, text } = generateDateTitle(yesterdayDate, '📋');
    return (
      <>
        <Emoji emoji={emoji} /> {text}
      </>
    );
  };

  // Convertir les métriques de deadline en AlertItem
  const convertDeadlineMetricsToAlertItems = (
    metrics: DeadlineMetrics | null
  ): AlertItem[] => {
    if (!metrics) return [];

    const urgentTasks = [
      ...metrics.overdue,
      ...metrics.critical,
      ...metrics.warning,
    ].sort((a, b) => {
      const urgencyOrder: Record<string, number> = {
        overdue: 0,
        critical: 1,
        warning: 2,
      };
      if (urgencyOrder[a.urgencyLevel] !== urgencyOrder[b.urgencyLevel]) {
        return urgencyOrder[a.urgencyLevel] - urgencyOrder[b.urgencyLevel];
      }
      return a.daysRemaining - b.daysRemaining;
    });

    return urgentTasks.map((task) => ({
      id: task.id,
      title: task.title,
      icon:
        task.urgencyLevel === 'overdue'
          ? '🔴'
          : task.urgencyLevel === 'critical'
            ? '🟠'
            : '🟡',
      urgency: task.urgencyLevel as 'low' | 'medium' | 'high' | 'critical',
      source: task.source,
      metadata:
        task.urgencyLevel === 'overdue'
          ? task.daysRemaining === -1
            ? 'En retard de 1 jour'
            : `En retard de ${Math.abs(task.daysRemaining)} jours`
          : task.urgencyLevel === 'critical'
            ? task.daysRemaining === 0
              ? "Échéance aujourd'hui"
              : task.daysRemaining === 1
                ? 'Échéance demain'
                : `Dans ${task.daysRemaining} jours`
            : `Dans ${task.daysRemaining} jours`,
    }));
  };

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[200px]">
          <div className="text-[var(--muted-foreground)] font-mono">
            Chargement du daily...
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="bg-[var(--destructive)]/10 border border-[var(--destructive)]/20 rounded-lg p-4 text-center">
          <p className="text-[var(--destructive)] font-mono mb-4">
            Erreur: {error}
          </p>
          <Button onClick={() => window.location.reload()} variant="primary">
            Réessayer
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[var(--background)]">
      {/* Header uniforme */}
      <Header
        title="TowerControl"
        subtitle="Daily - Gestion quotidienne"
        syncing={saving}
      />

      {/* Navigation Daily spécifique */}
      <div className="bg-[var(--card)]/50 border-b border-[var(--border)]/30">
        <div className="container mx-auto px-4 py-3">
          <div className="flex items-center justify-center gap-2">
            <Button
              onClick={goToPreviousDay}
              variant="ghost"
              size="sm"
              disabled={saving}
            >
              ←
            </Button>

            <div className="text-center min-w-[200px]">
              <div className="text-sm font-bold text-[var(--foreground)] font-mono">
                {formatCurrentDate()}
              </div>
              {!isTodayDate() && (
                <button
                  onClick={goToToday}
                  className="text-xs text-[var(--primary)] hover:text-[var(--primary)]/80 font-mono"
                >
                  Aller à aujourd&apos;hui
                </button>
              )}
            </div>

            <Button
              onClick={goToNextDay}
              variant="ghost"
              size="sm"
              disabled={saving}
            >
              →
            </Button>
          </div>
        </div>
      </div>

      {/* Rappel des échéances urgentes - Desktop uniquement */}
      <div className="hidden sm:block container mx-auto px-4 pt-4 pb-2">
        <AlertBanner
          title="Rappel - Tâches urgentes"
          items={convertDeadlineMetricsToAlertItems(
            initialDeadlineMetrics || null
          )}
          icon="⚠️"
          variant="warning"
          onItemClick={(item) => {
            // Rediriger vers la page Kanban avec la tâche sélectionnée
            window.location.href = `/kanban?taskId=${item.id}`;
          }}
        />
      </div>

      {/* Contenu principal */}
      <main className="container mx-auto px-4 py-6 sm:py-4">
        {/* Layout Mobile uniquement - Section Aujourd'hui en premier */}
        <div className="block sm:hidden">
          {dailyView && (
            <div className="space-y-6">
              {/* Section Aujourd'hui - Mobile First */}
              <DailySection
                title={getTodayTitle()}
                date={getTodayDate()}
                checkboxes={dailyView.today}
                onAddCheckbox={handleAddTodayCheckbox}
                onToggleCheckbox={handleToggleCheckbox}
                onUpdateCheckbox={handleUpdateCheckbox}
                onDeleteCheckbox={handleDeleteCheckbox}
                onReorderCheckboxes={handleReorderCheckboxes}
                onToggleAll={toggleAllToday}
                saving={saving}
                refreshing={refreshing}
              />

              {/* Calendrier en bas sur mobile */}
              <Calendar
                currentDate={currentDate}
                onDateSelect={handleDateSelect}
                markedDates={dailyDates}
                deadlineDates={deadlineDates}
                showTodayButton={true}
                showLegend={true}
              />

              {/* Section des tâches avec deadline pour la date sélectionnée - Mobile */}
              {deadlineTasks.length > 0 && (
                <Card variant="glass">
                  <CardHeader padding="sm" separator={false}>
                    <CardTitle size="sm" className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-[var(--destructive)]"></div>
                      Tâches à terminer
                    </CardTitle>
                  </CardHeader>
                  <CardContent padding="sm">
                    {loadingDeadlineTasks ? (
                      <div className="text-sm text-[var(--muted-foreground)] text-center py-4">
                        Chargement...
                      </div>
                    ) : (
                      <div className="space-y-2">
                        {deadlineTasks.map((task) => (
                          <TaskCard
                            key={task.id}
                            variant="compact"
                            title={task.title}
                            description={task.description}
                            tags={task.tags}
                            primaryTagId={task.primaryTagId}
                            priority={task.priority}
                            status={task.status}
                            dueDate={task.dueDate}
                            source={task.source}
                            jiraKey={task.jiraKey}
                            jiraProject={task.jiraProject}
                            jiraType={task.jiraType}
                            todosCount={task.todosCount}
                            availableTags={availableTags}
                            fontSize="small"
                            onClick={() => {
                              window.location.href = `/kanban?taskId=${task.id}`;
                            }}
                          />
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </div>

        {/* Layout Tablette/Desktop - Layout original */}
        <div className="hidden sm:block">
          <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
            {/* Calendrier - Desktop */}
            <div className="xl:col-span-1 space-y-6">
              <Calendar
                currentDate={currentDate}
                onDateSelect={handleDateSelect}
                markedDates={dailyDates}
                deadlineDates={deadlineDates}
                showTodayButton={true}
                showLegend={true}
              />

              {/* Section des tâches avec deadline pour la date sélectionnée */}
              {deadlineTasks.length > 0 && (
                <Card variant="glass">
                  <CardHeader padding="sm" separator={false}>
                    <CardTitle size="sm" className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-[var(--destructive)]"></div>
                      Tâches à terminer
                    </CardTitle>
                  </CardHeader>
                  <CardContent padding="sm">
                    {loadingDeadlineTasks ? (
                      <div className="text-sm text-[var(--muted-foreground)] text-center py-4">
                        Chargement...
                      </div>
                    ) : (
                      <div className="space-y-2">
                        {deadlineTasks.map((task) => (
                          <TaskCard
                            key={task.id}
                            variant="compact"
                            title={task.title}
                            description={task.description}
                            tags={task.tags}
                            primaryTagId={task.primaryTagId}
                            priority={task.priority}
                            status={task.status}
                            dueDate={task.dueDate}
                            source={task.source}
                            jiraKey={task.jiraKey}
                            jiraProject={task.jiraProject}
                            jiraType={task.jiraType}
                            todosCount={task.todosCount}
                            availableTags={availableTags}
                            fontSize="small"
                            onClick={() => {
                              window.location.href = `/kanban?taskId=${task.id}`;
                            }}
                          />
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}
            </div>

            {/* Sections daily - Desktop */}
            {dailyView && (
              <div className="xl:col-span-2 grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Section Hier - Desktop seulement */}
                <DailySection
                  title={getYesterdayTitle()}
                  date={getYesterdayDate()}
                  checkboxes={dailyView.yesterday}
                  onAddCheckbox={handleAddYesterdayCheckbox}
                  onToggleCheckbox={handleToggleCheckbox}
                  onUpdateCheckbox={handleUpdateCheckbox}
                  onDeleteCheckbox={handleDeleteCheckbox}
                  onReorderCheckboxes={handleReorderCheckboxes}
                  onToggleAll={toggleAllYesterday}
                  saving={saving}
                  refreshing={refreshing}
                />

                {/* Section Aujourd'hui - Desktop */}
                <DailySection
                  title={getTodayTitle()}
                  date={getTodayDate()}
                  checkboxes={dailyView.today}
                  onAddCheckbox={handleAddTodayCheckbox}
                  onToggleCheckbox={handleToggleCheckbox}
                  onUpdateCheckbox={handleUpdateCheckbox}
                  onDeleteCheckbox={handleDeleteCheckbox}
                  onReorderCheckboxes={handleReorderCheckboxes}
                  onToggleAll={toggleAllToday}
                  saving={saving}
                  refreshing={refreshing}
                />
              </div>
            )}
          </div>
        </div>

        {/* Section des tâches en attente */}
        <PendingTasksSection
          onToggleCheckbox={handleToggleCheckbox}
          onDeleteCheckbox={handleDeleteCheckbox}
          onRefreshDaily={refreshDailySilent}
          refreshTrigger={pendingRefreshTrigger}
          initialPendingTasks={initialPendingTasks}
        />

        {/* Footer avec stats - dans le flux normal */}
        {dailyView && (
          <Card className="mt-8 p-4">
            <div className="text-center text-sm text-[var(--muted-foreground)] font-mono">
              Daily pour {formatCurrentDate()}
              {' • '}
              {dailyView.yesterday.length + dailyView.today.length} tâche
              {dailyView.yesterday.length + dailyView.today.length > 1
                ? 's'
                : ''}{' '}
              au total
              {' • '}
              {dailyView.yesterday.filter((cb) => cb.isChecked).length +
                dailyView.today.filter((cb) => cb.isChecked).length}{' '}
              complétée
              {dailyView.yesterday.filter((cb) => cb.isChecked).length +
                dailyView.today.filter((cb) => cb.isChecked).length >
              1
                ? 's'
                : ''}
            </div>
          </Card>
        )}
      </main>
    </div>
  );
}
