'use client';

import { useMemo } from 'react';
import { useTasksContext } from '@/contexts/TasksContext';
import { KanbanFilters } from './KanbanFilters';

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

export function JiraQuickFilter({ filters, onFiltersChange }: JiraQuickFilterProps) {
  const { regularTasks } = useTasksContext();

  // Vérifier s'il y a des tâches Jira dans le système
  const hasJiraTasks = useMemo(() => {
    return regularTasks.some(task => task.source === 'jira');
  }, [regularTasks]);

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

  // Déterminer l'état actuel
  const currentMode = filters.showJiraOnly ? 'show' : filters.hideJiraTasks ? 'hide' : 'all';

  const handleJiraCycle = () => {
    const updates: Partial<KanbanFilters> = {};
    
    // Cycle : All -> Jira only -> No Jira -> All
    switch (currentMode) {
      case 'all':
        // All -> Jira only
        updates.showJiraOnly = true;
        updates.hideJiraTasks = false;
        break;
      case 'show':
        // Jira only -> No Jira
        updates.showJiraOnly = false;
        updates.hideJiraTasks = true;
        break;
      case 'hide':
        // No Jira -> All
        updates.showJiraOnly = false;
        updates.hideJiraTasks = false;
        break;
    }
    
    onFiltersChange({ ...filters, ...updates });
  };

  // Définir l'apparence selon l'état
  const getButtonStyle = () => {
    switch (currentMode) {
      case 'show':
        return 'bg-[var(--primary)]/20 text-[var(--primary)] border border-[var(--primary)]/30';
      case 'hide':
        return 'bg-red-500/20 text-red-400 border border-red-400/30';
      default:
        return 'bg-[var(--card)] text-[var(--muted-foreground)] border border-[var(--border)] hover:border-[var(--primary)]/50';
    }
  };

  const getButtonContent = () => {
    switch (currentMode) {
      case 'show':
        return { icon: '🔹', text: 'Jira only' };
      case 'hide':
        return { icon: '🚫', text: 'No Jira' };
      default:
        return { icon: '🔌', text: 'All tasks' };
    }
  };

  const getTooltip = () => {
    switch (currentMode) {
      case 'all':
        return 'Cliquer pour afficher seulement Jira';
      case 'show':
        return 'Cliquer pour masquer Jira';
      case 'hide':
        return 'Cliquer pour afficher tout';
      default:
        return 'Filtrer les tâches Jira';
    }
  };

  const content = getButtonContent();

  return (
    <button
      onClick={handleJiraCycle}
      className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-mono transition-all ${getButtonStyle()}`}
      title={getTooltip()}
    >
      <span>{content.icon}</span>
      {content.text}
    </button>
  );
}
