'use client';

import { useMemo } from 'react';
import { Button, FilterChip } from '@/components/ui';
import { useTasksContext } from '@/contexts/TasksContext';
import type { KanbanFilters } from '@/lib/types';
import {
  Plug,
  Circle,
  X,
  ClipboardList,
  Sparkles,
  BookOpen,
  FileText,
  Bug,
  Wrench,
  Settings,
} from 'lucide-react';

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

export function JiraFilters({ filters, onFiltersChange }: JiraFiltersProps) {
  const { regularTasks } = useTasksContext();

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

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

  const availableJiraTypes = useMemo(() => {
    const types = new Set<string>();
    regularTasks.forEach((task) => {
      if (task.source === 'jira' && task.jiraType) {
        types.add(task.jiraType);
      }
    });
    return Array.from(types).sort();
  }, [regularTasks]);

  // Calculer les compteurs pour les projets Jira
  const jiraProjectCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    availableJiraProjects.forEach((project) => {
      counts[project] = regularTasks.filter(
        (task) => task.source === 'jira' && task.jiraProject === project
      ).length;
    });
    return counts;
  }, [regularTasks, availableJiraProjects]);

  // Calculer les compteurs pour les types Jira
  const jiraTypeCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    availableJiraTypes.forEach((type) => {
      counts[type] = regularTasks.filter(
        (task) => task.source === 'jira' && task.jiraType === type
      ).length;
    });
    return counts;
  }, [regularTasks, availableJiraTypes]);

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

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

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

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

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

  const handleJiraTypeToggle = (type: string) => {
    const currentTypes = filters.jiraTypes || [];
    const newTypes = currentTypes.includes(type)
      ? currentTypes.filter((t) => t !== type)
      : [...currentTypes, type];

    onFiltersChange({
      ...filters,
      jiraTypes: newTypes,
    });
  };

  // Si pas de tâches Jira, on n'affiche rien
  if (!hasJiraTasks) {
    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">
          <Plug size={12} className="inline mr-1" /> Jira
        </label>

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

      {/* Projets et Types en 2 colonnes */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Projets Jira */}
        {availableJiraProjects.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">
              {availableJiraProjects.map((project) => (
                <FilterChip
                  key={project}
                  onClick={() => handleJiraProjectToggle(project)}
                  variant={
                    filters.jiraProjects?.includes(project)
                      ? 'selected'
                      : 'default'
                  }
                  count={jiraProjectCounts[project]}
                  icon={<ClipboardList size={14} />}
                >
                  {project}
                </FilterChip>
              ))}
            </div>
          </div>
        )}

        {/* Types Jira */}
        {availableJiraTypes.length > 0 && (
          <div>
            <label className="block text-xs font-medium text-[var(--muted-foreground)] mb-2">
              Types
            </label>
            <div className="flex flex-wrap gap-1">
              {availableJiraTypes.map((type) => {
                const getTypeIcon = (type: string) => {
                  switch (type) {
                    case 'Feature':
                      return <Sparkles size={14} />;
                    case 'Story':
                      return <BookOpen size={14} />;
                    case 'Task':
                      return <FileText size={14} />;
                    case 'Bug':
                      return <Bug size={14} />;
                    case 'Support':
                      return <Wrench size={14} />;
                    case 'Enabler':
                      return <Settings size={14} />;
                    default:
                      return <ClipboardList size={14} />;
                  }
                };

                return (
                  <FilterChip
                    key={type}
                    onClick={() => handleJiraTypeToggle(type)}
                    variant={
                      filters.jiraTypes?.includes(type) ? 'selected' : 'default'
                    }
                    count={jiraTypeCounts[type]}
                    icon={getTypeIcon(type)}
                  >
                    {type}
                  </FilterChip>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
