'use client';

import { useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { KanbanBoardContainer } from '@/components/kanban/BoardContainer';
import { Header } from '@/components/ui/Header';
import { TasksProvider, useTasksContext } from '@/contexts/TasksContext';
import { useUserPreferences } from '@/contexts/UserPreferencesContext';
import { Task, Tag } from '@/lib/types';
import { CreateTaskData } from '@/clients/tasks-client';
import { CreateTaskForm } from '@/components/forms/CreateTaskForm';
import { MobileControls } from '@/components/kanban/MobileControls';
import { DesktopControls } from '@/components/kanban/DesktopControls';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useGlobalKeyboardShortcuts } from '@/hooks/useGlobalKeyboardShortcuts';

interface KanbanPageClientProps {
  initialTasks: Task[];
  initialTags: (Tag & { usage: number })[];
}

function KanbanPageContent() {
  const {
    syncing,
    createTask,
    activeFiltersCount,
    kanbanFilters,
    setKanbanFilters,
  } = useTasksContext();
  const { preferences, updateViewPreferences, toggleFontSize } =
    useUserPreferences();
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const isMobile = useIsMobile(768); // Tailwind md breakpoint
  const searchParams = useSearchParams();
  const taskIdFromUrl = searchParams.get('taskId');

  // Extraire les préférences du context
  const showFilters = preferences.viewPreferences.showFilters;
  const showObjectives = preferences.viewPreferences.showObjectives;
  const compactView = preferences.viewPreferences.compactView;
  const swimlanesByTags = preferences.viewPreferences.swimlanesByTags;

  // Handlers pour les toggles (sauvegarde automatique via le context)
  const handleToggleFilters = () => {
    updateViewPreferences({ showFilters: !showFilters });
  };

  const handleToggleObjectives = () => {
    updateViewPreferences({ showObjectives: !showObjectives });
  };

  const handleToggleCompactView = () => {
    updateViewPreferences({ compactView: !compactView });
  };

  const handleToggleSwimlanes = () => {
    updateViewPreferences({ swimlanesByTags: !swimlanesByTags });
  };

  const handleToggleDueDateFilter = () => {
    setKanbanFilters({
      ...kanbanFilters,
      showWithDueDate: !kanbanFilters.showWithDueDate,
    });
  };

  // Handler pour la création de tâche depuis la barre de contrôles
  const handleCreateTask = async (data: CreateTaskData) => {
    await createTask(data);
    setIsCreateModalOpen(false);
  };

  // Raccourcis clavier globaux pour la page Kanban
  useGlobalKeyboardShortcuts({
    onCreateTask: () => setIsCreateModalOpen(true),
    onToggleFilters: handleToggleFilters,
    onToggleCompactView: handleToggleCompactView,
    onToggleSwimlanes: handleToggleSwimlanes,
    onToggleObjectives: handleToggleObjectives,
    onToggleDueDateFilter: handleToggleDueDateFilter,
    onToggleFontSize: toggleFontSize,
    onOpenSearch: () => {
      // Focus sur le champ de recherche dans les contrôles desktop
      const searchInput = document.querySelector(
        'input[placeholder*="Rechercher"]'
      ) as HTMLInputElement;
      searchInput?.focus();
    },
  });

  return (
    <div className="min-h-screen bg-[var(--background)]">
      <Header
        title="Kanban Board"
        subtitle="Gestionnaire de tâches"
        syncing={syncing}
      />

      {/* Barre de contrôles responsive */}
      {isMobile ? (
        <MobileControls
          showFilters={showFilters}
          showObjectives={showObjectives}
          compactView={compactView}
          activeFiltersCount={activeFiltersCount}
          kanbanFilters={kanbanFilters}
          onToggleFilters={handleToggleFilters}
          onToggleObjectives={handleToggleObjectives}
          onToggleCompactView={handleToggleCompactView}
          onFiltersChange={setKanbanFilters}
          onCreateTask={() => setIsCreateModalOpen(true)}
        />
      ) : (
        <DesktopControls
          showFilters={showFilters}
          showObjectives={showObjectives}
          compactView={compactView}
          swimlanesByTags={swimlanesByTags}
          activeFiltersCount={activeFiltersCount}
          kanbanFilters={kanbanFilters}
          onToggleFilters={handleToggleFilters}
          onToggleObjectives={handleToggleObjectives}
          onToggleCompactView={handleToggleCompactView}
          onToggleSwimlanes={handleToggleSwimlanes}
          onFiltersChange={setKanbanFilters}
          onCreateTask={() => setIsCreateModalOpen(true)}
        />
      )}

      <main className="h-[calc(100vh-160px)]">
        <KanbanBoardContainer
          showFilters={showFilters}
          showObjectives={showObjectives}
          initialTaskIdToEdit={taskIdFromUrl}
        />
      </main>

      {/* Modal de création de tâche */}
      <CreateTaskForm
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSubmit={handleCreateTask}
        loading={false}
      />
    </div>
  );
}

export function KanbanPageClient({
  initialTasks,
  initialTags,
}: KanbanPageClientProps) {
  return (
    <TasksProvider initialTasks={initialTasks} initialTags={initialTags}>
      <KanbanPageContent />
    </TasksProvider>
  );
}
