'use client';

import { useState } from 'react';
import { TaskPriority, TaskStatus } from '@/lib/types';
import {
  SearchInput,
  ToggleButton,
  ControlPanel,
  ControlSection,
  ControlGroup,
  FilterSummary,
  Dropdown,
} from '@/components/ui';
import { useTasksContext } from '@/contexts/TasksContext';
import { SORT_OPTIONS } from '@/lib/sort-config';
import { SortIcon } from '@/components/ui/SortIcon';
import { useUserPreferences } from '@/contexts/UserPreferencesContext';
import { useIsMobile } from '@/hooks/useIsMobile';
import { JiraFilters } from './filters/JiraFilters';
import { TfsFilters } from './filters/TfsFilters';
import { PriorityFilters } from './filters/PriorityFilters';
import { TagFilters } from './filters/TagFilters';
import { GeneralFilters } from './filters/GeneralFilters';
import { ColumnFilters } from './filters/ColumnFilters';
import { Layout, Grid3X3, Menu } from 'lucide-react';

import type { KanbanFilters } from '@/lib/types';

interface KanbanFiltersProps {
  filters: KanbanFilters;
  onFiltersChange: (filters: KanbanFilters) => void;
  hiddenStatuses?: Set<TaskStatus>;
  onToggleStatusVisibility?: (status: TaskStatus) => void;
}

export function KanbanFilters({
  filters,
  onFiltersChange,
  hiddenStatuses: propsHiddenStatuses,
  onToggleStatusVisibility,
}: KanbanFiltersProps) {
  const { regularTasks, activeFiltersCount, oldCompletedTasksCount } =
    useTasksContext();
  const { preferences, toggleColumnVisibility } = useUserPreferences();

  // Utiliser les props si disponibles, sinon utiliser le context
  const hiddenStatuses =
    propsHiddenStatuses || new Set(preferences.columnVisibility.hiddenStatuses);
  const toggleStatusVisibility =
    onToggleStatusVisibility || toggleColumnVisibility;
  const [isSortOpen, setIsSortOpen] = useState(false);
  const isMobile = useIsMobile(768); // Tailwind md breakpoint

  // Handler pour la recherche avec debounce intégré
  const handleSearchChange = (search: string) => {
    onFiltersChange({ ...filters, search: search || undefined });
  };

  const handleTagToggle = (tagName: string) => {
    const currentTags = filters.tags || [];
    const newTags = currentTags.includes(tagName)
      ? currentTags.filter((t) => t !== tagName)
      : [...currentTags, tagName];

    onFiltersChange({
      ...filters,
      tags: newTags,
    });
  };

  const handlePriorityToggle = (priority: TaskPriority) => {
    const currentPriorities = filters.priorities || [];
    const newPriorities = currentPriorities.includes(priority)
      ? currentPriorities.filter((p) => p !== priority)
      : [...currentPriorities, priority];

    onFiltersChange({
      ...filters,
      priorities: newPriorities,
    });
  };

  const handleSwimlanesToggle = () => {
    // Cycle entre les 3 modes : Normal → Par tags → Par priorité → Normal
    if (!filters.swimlanesByTags) {
      // Normal → Par tags
      onFiltersChange({
        ...filters,
        swimlanesByTags: true,
        swimlanesMode: 'tags',
      });
    } else if (filters.swimlanesMode === 'tags') {
      // Par tags → Par priorité
      onFiltersChange({
        ...filters,
        swimlanesByTags: true,
        swimlanesMode: 'priority',
      });
    } else {
      // Par priorité → Normal
      onFiltersChange({
        ...filters,
        swimlanesByTags: false,
        swimlanesMode: undefined,
      });
    }
  };

  const handleSortChange = (sortKey: string) => {
    onFiltersChange({
      ...filters,
      sortBy: sortKey,
    });
  };

  const handleClearFilters = () => {
    onFiltersChange({});
  };

  const handleDueDateFilterToggle = () => {
    onFiltersChange({
      ...filters,
      showWithDueDate: !filters.showWithDueDate,
    });
  };

  const handleCompletedLast7DaysFilterToggle = () => {
    onFiltersChange({
      ...filters,
      showCompletedLast7Days: !filters.showCompletedLast7Days,
    });
  };

  const handleHideCompletedOlderThan15DaysFilterToggle = () => {
    onFiltersChange({
      ...filters,
      hideCompletedOlderThan15Days: !filters.hideCompletedOlderThan15Days,
    });
  };

  return (
    <ControlPanel className="bg-[var(--card)]/50 border-b border-[var(--border)]/50 backdrop-blur-sm">
      <div className="container mx-auto px-6 py-4">
        {/* Header avec recherche et bouton expand */}
        <ControlSection>
          <div className="flex-1 max-w-md">
            <SearchInput
              value={filters.search || ''}
              onChange={handleSearchChange}
              placeholder="Rechercher des tâches..."
            />
          </div>

          {/* Menu swimlanes - masqué sur mobile */}
          {!isMobile && (
            <ControlGroup>
              <ToggleButton
                variant="warning"
                isActive={!!filters.swimlanesByTags}
                onClick={handleSwimlanesToggle}
                title="Mode d'affichage"
                icon={
                  filters.swimlanesByTags ? (
                    <Layout className="w-4 h-4" />
                  ) : (
                    <Grid3X3 className="w-4 h-4" />
                  )
                }
              >
                {!filters.swimlanesByTags
                  ? 'Normal'
                  : filters.swimlanesMode === 'priority'
                    ? 'Par priorité'
                    : 'Par tags'}
              </ToggleButton>
            </ControlGroup>
          )}

          {/* Bouton de tri */}
          <ControlGroup>
            <Dropdown
              open={isSortOpen}
              onOpenChange={setIsSortOpen}
              trigger={
                <>
                  <Menu size={14} className="inline mr-1" /> Tris
                </>
              }
              triggerClassName="h-[34px] py-[5px]"
              content={
                <div className="max-h-64 overflow-y-auto">
                  {SORT_OPTIONS.map((option) => (
                    <button
                      key={option.key}
                      onClick={() => handleSortChange(option.key)}
                      className={`w-full px-3 py-2 text-left text-xs font-mono hover:bg-[var(--card-hover)] transition-colors flex items-center gap-2 ${
                        (filters.sortBy || 'priority-desc') === option.key
                          ? 'bg-cyan-600/20 text-cyan-400 border-l-2 border-cyan-400'
                          : 'text-[var(--muted-foreground)]'
                      }`}
                    >
                      <span className="text-base">
                        <SortIcon iconName={option.iconName} size={16} />
                      </span>
                      <span>{option.label}</span>
                    </button>
                  ))}
                </div>
              }
              placement="bottom-start"
              className="w-80"
            />
          </ControlGroup>
        </ControlSection>

        {/* Filtres étendus */}
        <div className="mt-4 border-t border-[var(--border)]/50 pt-4">
          {/* Layout optimisé : 3 colonnes avec Tags très large à droite */}
          <div className="grid grid-cols-1 xl:grid-cols-[280px_1fr_300px] gap-4 lg:gap-6 items-start">
            {/* Colonne 1 : Priorités + Généraux */}
            <div className="space-y-4">
              <PriorityFilters
                selectedPriorities={filters.priorities}
                onPriorityToggle={handlePriorityToggle}
              />

              <GeneralFilters
                showWithDueDate={filters.showWithDueDate}
                showCompletedLast7Days={filters.showCompletedLast7Days}
                hideCompletedOlderThan15Days={
                  filters.hideCompletedOlderThan15Days
                }
                oldCompletedTasksCount={oldCompletedTasksCount || 0}
                onDueDateFilterToggle={handleDueDateFilterToggle}
                onCompletedLast7DaysFilterToggle={
                  handleCompletedLast7DaysFilterToggle
                }
                onHideCompletedOlderThan15DaysFilterToggle={
                  handleHideCompletedOlderThan15DaysFilterToggle
                }
              />
            </div>

            {/* Colonne 2 : Tags - Espace restant maximum */}
            <TagFilters
              selectedTags={filters.tags}
              onTagToggle={handleTagToggle}
            />

            {/* Colonne 3 : Visibilité des colonnes */}
            <ColumnFilters
              hiddenStatuses={hiddenStatuses}
              onToggleStatus={toggleStatusVisibility}
              tasks={regularTasks}
            />
          </div>

          {/* Deuxième ligne : TFS et Jira côte à côte */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-2">
            {/* Filtres TFS */}
            <TfsFilters filters={filters} onFiltersChange={onFiltersChange} />

            {/* Filtres Jira */}
            <JiraFilters filters={filters} onFiltersChange={onFiltersChange} />
          </div>

          {/* Résumé des filtres actifs */}
          <FilterSummary
            filters={filters}
            activeFiltersCount={activeFiltersCount}
            onClearFilters={handleClearFilters}
            className="mt-6"
          />
        </div>
      </div>
    </ControlPanel>
  );
}
