'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import {
  Button,
  ToggleButton,
  SearchInput,
  ControlPanel,
  ControlSection,
  ControlGroup,
} from '@/components/ui';
import { IntegrationFilter } from '@/components/dashboard/IntegrationFilter';
import { FontSizeToggle } from '@/components/ui/FontSizeToggle';
import type { KanbanFilters } from '@/lib/types';
import {
  Target,
  Plus,
  List,
  Grid3X3,
  Layout,
  Clock,
  Search,
  Settings,
} from 'lucide-react';

interface DesktopControlsProps {
  showFilters: boolean;
  showObjectives: boolean;
  compactView: boolean;
  swimlanesByTags: boolean;
  activeFiltersCount: number;
  kanbanFilters: KanbanFilters;
  onToggleFilters: () => void;
  onToggleObjectives: () => void;
  onToggleCompactView: () => void;
  onToggleSwimlanes: () => void;
  onFiltersChange: (filters: KanbanFilters) => void;
  onCreateTask: () => void;
}

export function DesktopControls({
  showFilters,
  showObjectives,
  compactView,
  swimlanesByTags,
  activeFiltersCount,
  kanbanFilters,
  onToggleFilters,
  onToggleObjectives,
  onToggleCompactView,
  onToggleSwimlanes,
  onFiltersChange,
  onCreateTask,
}: DesktopControlsProps) {
  // État local pour la recherche pour une saisie fluide
  const [localSearch, setLocalSearch] = useState(kanbanFilters.search || '');
  const searchTimeoutRef = useRef<number | undefined>(undefined);

  // Fonction debouncée pour mettre à jour les filtres
  const debouncedSearchChange = useCallback(
    (search: string) => {
      if (searchTimeoutRef.current) {
        window.clearTimeout(searchTimeoutRef.current);
      }

      searchTimeoutRef.current = window.setTimeout(() => {
        onFiltersChange({ ...kanbanFilters, search: search || undefined });
      }, 300);
    },
    [kanbanFilters, onFiltersChange]
  );

  const handleSearchChange = (search: string) => {
    setLocalSearch(search);
    debouncedSearchChange(search);
  };

  // Synchroniser l'état local quand les filtres changent de l'extérieur
  useEffect(() => {
    setLocalSearch(kanbanFilters.search || '');
  }, [kanbanFilters.search]);

  // Nettoyer le timeout au démontage
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        window.clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);

  const handleDueDateFilterToggle = () => {
    onFiltersChange({
      ...kanbanFilters,
      showWithDueDate: !kanbanFilters.showWithDueDate,
    });
  };
  return (
    <ControlPanel>
      {/* Layout responsive : deux lignes sur tablette, une ligne sur desktop */}
      <div className="flex flex-col lg:flex-row lg:items-center gap-4 lg:gap-0 w-full">
        {/* Section gauche : Recherche + Boutons principaux */}
        <ControlSection className="items-center gap-2">
          {/* Champ de recherche avec icône */}
          <div className="relative flex-1 min-w-0">
            <SearchInput
              value={localSearch}
              onChange={handleSearchChange}
              placeholder="Rechercher"
              className="pl-10"
            />
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-[var(--muted-foreground)] pointer-events-none" />
          </div>

          <ControlGroup>
            <ToggleButton
              variant="primary"
              isActive={showFilters}
              count={activeFiltersCount}
              onClick={onToggleFilters}
              icon={<Settings className="w-4 h-4" />}
            >
              Filtres
            </ToggleButton>

            <ToggleButton
              variant="accent"
              isActive={showObjectives}
              onClick={onToggleObjectives}
              icon={<Target className="w-4 h-4" />}
            >
              Objectifs
            </ToggleButton>

            <ToggleButton
              variant="cyan"
              isActive={kanbanFilters.showWithDueDate}
              onClick={handleDueDateFilterToggle}
              title={
                kanbanFilters.showWithDueDate
                  ? 'Afficher toutes les tâches'
                  : 'Afficher seulement les tâches avec échéance'
              }
              icon={<Clock className="w-4 h-4" />}
            >
              Échéance
            </ToggleButton>
          </ControlGroup>
        </ControlSection>

        {/* Section droite : Raccourcis + Bouton Nouvelle tâche */}
        <ControlSection className="justify-between lg:justify-start items-center">
          <ControlGroup className="border-l border-[var(--border)] ml-2 pl-2 pr-4">
            {/* Raccourcis Sources (Jira & TFS) */}
            <IntegrationFilter
              filters={kanbanFilters}
              onFiltersChange={onFiltersChange}
            />

            <ToggleButton
              variant="secondary"
              isActive={compactView}
              onClick={onToggleCompactView}
              title={compactView ? 'Vue détaillée' : 'Vue compacte'}
              icon={
                compactView ? (
                  <List className="w-4 h-4" />
                ) : (
                  <Grid3X3 className="w-4 h-4" />
                )
              }
              className="h-[33px]"
            >
              {compactView ? 'Détaillée' : 'Compacte'}
            </ToggleButton>

            <ToggleButton
              variant="warning"
              isActive={swimlanesByTags}
              onClick={onToggleSwimlanes}
              title={swimlanesByTags ? 'Vue standard' : 'Vue swimlanes'}
              icon={
                swimlanesByTags ? (
                  <Layout className="w-4 h-4" />
                ) : (
                  <Grid3X3 className="w-4 h-4" />
                )
              }
              className="h-[33px]"
            >
              {swimlanesByTags ? 'Standard' : 'Swimlanes'}
            </ToggleButton>

            {/* Font Size Toggle */}
            <FontSizeToggle />
          </ControlGroup>

          {/* Bouton d'ajout de tâche */}
          <Button
            variant="primary"
            onClick={onCreateTask}
            className="flex items-center gap-2 h-[34px] max-w-[180px] truncate"
          >
            <Plus className="w-4 h-4" />
            Nouvelle tâche
          </Button>
        </ControlSection>
      </div>
    </ControlPanel>
  );
}
