'use client';

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 { ProductivityMetrics } from '@/services/analytics/analytics';
import { DeadlineMetrics } from '@/services/analytics/deadline-analytics';
import { useGlobalKeyboardShortcuts } from '@/hooks/useGlobalKeyboardShortcuts';

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


function HomePageContent({ productivityMetrics, deadlineMetrics }: { 
  productivityMetrics: ProductivityMetrics;
  deadlineMetrics: DeadlineMetrics;
}) {
  const { stats, syncing, createTask, tasks } = useTasksContext();

  // 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">
        {/* Statistiques */}
        <DashboardStats stats={stats} />
        
        {/* Actions rapides */}
        <QuickActions onCreateTask={handleCreateTask} />
        
        {/* Analytics et métriques */}
        <ProductivityAnalytics 
          metrics={productivityMetrics}
          deadlineMetrics={deadlineMetrics}
        />
        
        {/* Tâches récentes */}
        <RecentTasks tasks={tasks} />
      </main>
    </div>
  );
}

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