'use client';

import { useState } from 'react';
import { Header } from '@/components/ui/Header';
import { TasksProvider, useTasksContext } from '@/contexts/TasksContext';
import { Task, Tag, TaskStats } from '@/lib/types';
import { CreateTaskData } from '@/clients/tasks-client';
import { DashboardStats } from '@/components/dashboard/DashboardStats';
import { QuickActions } from '@/components/dashboard/QuickActions';
import { RecentTasks } from '@/components/dashboard/RecentTasks';
import { ProductivityAnalytics } from '@/components/dashboard/ProductivityAnalytics';
import { WelcomeSection } from '@/components/dashboard/WelcomeSection';
import { IntegrationFilter } from '@/components/dashboard/IntegrationFilter';
import { ProductivityMetrics } from '@/services/analytics/analytics';
import { DeadlineMetrics } from '@/services/analytics/deadline-analytics';
import { TagDistributionMetrics } from '@/services/analytics/tag-analytics';
import { useGlobalKeyboardShortcuts } from '@/hooks/useGlobalKeyboardShortcuts';

interface HomePageClientProps {
  initialTasks: Task[];
  initialTags: (Tag & { usage: number })[];
  initialStats: TaskStats;
  productivityMetrics: ProductivityMetrics;
  deadlineMetrics: DeadlineMetrics;
  tagMetrics: TagDistributionMetrics;
}

function HomePageContent({
  productivityMetrics,
  deadlineMetrics,
  tagMetrics,
}: {
  productivityMetrics: ProductivityMetrics;
  deadlineMetrics: DeadlineMetrics;
  tagMetrics: TagDistributionMetrics;
}) {
  const { syncing, createTask, tasks } = useTasksContext();
  const [selectedSources, setSelectedSources] = useState<string[]>([]);
  const [hiddenSources, setHiddenSources] = useState<string[]>([]);

  // Handler pour la création de tâche
  const handleCreateTask = async (data: CreateTaskData) => {
    await createTask(data);
  };

  // Raccourcis clavier globaux pour la page Dashboard
  useGlobalKeyboardShortcuts({
    onOpenSearch: () => {
      // Focus sur le champ de recherche s'il existe, sinon naviguer vers Kanban
      const searchInput = document.querySelector(
        'input[placeholder*="Rechercher"]'
      ) as HTMLInputElement;
      if (searchInput) {
        searchInput.focus();
      } else {
        // Naviguer vers Kanban où il y a une recherche
        window.location.href = '/kanban';
      }
    },
  });

  return (
    <div className="min-h-screen bg-[var(--background)]">
      <Header
        title="TowerControl"
        subtitle="Dashboard - Vue d'ensemble"
        syncing={syncing}
      />

      <main className="container mx-auto px-6 py-8">
        {/* Section de bienvenue */}
        <WelcomeSection />

        {/* Filtre d'intégrations */}
        <div className="flex justify-end mb-6">
          <IntegrationFilter
            selectedSources={selectedSources}
            onSourcesChange={setSelectedSources}
            hiddenSources={hiddenSources}
            onHiddenSourcesChange={setHiddenSources}
            alignRight={true}
          />
        </div>

        {/* Statistiques */}
        <DashboardStats
          selectedSources={selectedSources}
          hiddenSources={hiddenSources}
        />

        {/* Actions rapides */}
        <QuickActions onCreateTask={handleCreateTask} />

        {/* Analytics et métriques */}
        <ProductivityAnalytics
          metrics={productivityMetrics}
          deadlineMetrics={deadlineMetrics}
          tagMetrics={tagMetrics}
          selectedSources={selectedSources}
          hiddenSources={hiddenSources}
        />

        {/* Tâches récentes */}
        <RecentTasks
          tasks={tasks}
          selectedSources={selectedSources}
          hiddenSources={hiddenSources}
        />
      </main>
    </div>
  );
}

export function HomePageClient({
  initialTasks,
  initialTags,
  initialStats,
  productivityMetrics,
  deadlineMetrics,
  tagMetrics,
}: HomePageClientProps) {
  return (
    <TasksProvider
      initialTasks={initialTasks}
      initialTags={initialTags}
      initialStats={initialStats}
    >
      <HomePageContent
        productivityMetrics={productivityMetrics}
        deadlineMetrics={deadlineMetrics}
        tagMetrics={tagMetrics}
      />
    </TasksProvider>
  );
}
