'use client';

import { useMemo } from 'react';
import { Button, FilterChip } from '@/components/ui';
import { useTasksContext } from '@/contexts/TasksContext';
import type { KanbanFilters } from '@/lib/types';
import { Package, Square, X, ClipboardList } from 'lucide-react';

interface TfsFiltersProps {
  filters: KanbanFilters;
  onFiltersChange: (filters: KanbanFilters) => void;
}

export function TfsFilters({ filters, onFiltersChange }: TfsFiltersProps) {
  const { regularTasks } = useTasksContext();

  // Vérifier s'il y a des tâches TFS dans le système (même masquées)
  const hasTfsTasks = regularTasks.some((task) => task.source === 'tfs');

  // Récupérer les projets TFS disponibles dans toutes les tâches
  const availableTfsProjects = useMemo(() => {
    const projects = new Set<string>();
    regularTasks.forEach((task) => {
      if (task.source === 'tfs' && task.tfsProject) {
        projects.add(task.tfsProject);
      }
    });
    return Array.from(projects).sort();
  }, [regularTasks]);

  // Calculer les compteurs pour les projets TFS
  const tfsProjectCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    availableTfsProjects.forEach((project) => {
      counts[project] = regularTasks.filter(
        (task) => task.source === 'tfs' && task.tfsProject === project
      ).length;
    });
    return counts;
  }, [regularTasks, availableTfsProjects]);

  const handleTfsToggle = (mode: 'show' | 'hide' | 'all') => {
    const updates: Partial<KanbanFilters> = {};

    switch (mode) {
      case 'show':
        updates.showTfsOnly = true;
        updates.hideTfsTasks = false;
        // Désactiver les filtres Jira conflictuels
        updates.showJiraOnly = false;
        break;
      case 'hide':
        updates.showTfsOnly = false;
        updates.hideTfsTasks = true;
        // Désactiver les filtres Jira conflictuels
        updates.hideJiraTasks = false;
        break;
      case 'all':
        updates.showTfsOnly = false;
        updates.hideTfsTasks = false;
        // Ne pas toucher aux filtres Jira
        break;
    }

    onFiltersChange({ ...filters, ...updates });
  };

  const handleTfsProjectToggle = (project: string) => {
    const currentProjects = filters.tfsProjects || [];
    const newProjects = currentProjects.includes(project)
      ? currentProjects.filter((p) => p !== project)
      : [...currentProjects, project];

    onFiltersChange({
      ...filters,
      tfsProjects: newProjects,
    });
  };

  // Si pas de tâches TFS, on n'affiche rien
  if (!hasTfsTasks) {
    return null;
  }

  return (
    <div className="border-t border-[var(--border)]/30 pt-4 mt-4">
      <div className="flex items-center gap-4 mb-3">
        <label className="block text-xs font-mono font-medium text-[var(--muted-foreground)] uppercase tracking-wider">
          <Package size={12} className="inline mr-1" /> TFS
        </label>

        {/* Toggle TFS Show/Hide - inline avec le titre */}
        <div className="flex gap-1">
          <Button
            variant={filters.showTfsOnly ? 'primary' : 'ghost'}
            onClick={() => handleTfsToggle('show')}
            size="sm"
            className="text-xs px-2 py-1 h-auto"
          >
            <Square size={12} className="inline mr-1" /> Seul
          </Button>
          <Button
            variant={filters.hideTfsTasks ? 'danger' : 'ghost'}
            onClick={() => handleTfsToggle('hide')}
            size="sm"
            className="text-xs px-2 py-1 h-auto"
          >
            <X size={12} className="inline mr-1" /> Mask
          </Button>
          <Button
            variant={
              !filters.showTfsOnly && !filters.hideTfsTasks
                ? 'primary'
                : 'ghost'
            }
            onClick={() => handleTfsToggle('all')}
            size="sm"
            className="text-xs px-2 py-1 h-auto"
          >
            <ClipboardList size={12} className="inline mr-1" /> All
          </Button>
        </div>
      </div>

      {/* Projets TFS */}
      {availableTfsProjects.length > 0 && (
        <div>
          <label className="block text-xs font-medium text-[var(--muted-foreground)] mb-2">
            Projets
          </label>
          <div className="flex flex-wrap gap-1">
            {availableTfsProjects.map((project) => (
              <FilterChip
                key={project}
                onClick={() => handleTfsProjectToggle(project)}
                variant={
                  filters.tfsProjects?.includes(project)
                    ? 'selected'
                    : 'default'
                }
                count={tfsProjectCounts[project]}
                icon={<Package size={14} />}
              >
                {project}
              </FilterChip>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
