'use client';

import { useState, useMemo } from 'react';
import { Link, Circle, Square, Hand } from 'lucide-react';
import { useTasksContext } from '@/contexts/TasksContext';
import { Dropdown, Button } from '@/components/ui';
import type { KanbanFilters } from '@/lib/types';

interface IntegrationFilterProps {
  // Interface pour Kanban (nouvelle)
  filters?: KanbanFilters;
  onFiltersChange?: (filters: KanbanFilters) => void;

  // Interface pour Dashboard (ancienne)
  selectedSources?: string[];
  onSourcesChange?: (sources: string[]) => void;
  hiddenSources?: string[];
  onHiddenSourcesChange?: (sources: string[]) => void;

  // Alignement du dropdown
  alignRight?: boolean;
}

interface SourceOption {
  id: 'jira' | 'tfs' | 'manual';
  label: string;
  icon: React.ReactNode;
  hasTasks: boolean;
}

type FilterMode = 'all' | 'show' | 'hide';

export function IntegrationFilter({
  filters,
  onFiltersChange,
  selectedSources,
  onSourcesChange,
  hiddenSources,
  onHiddenSourcesChange,
  alignRight = false,
}: IntegrationFilterProps) {
  const { regularTasks, pinnedTasks } = useTasksContext();
  const [isOpen, setIsOpen] = useState(false);

  // Vérifier quelles sources ont des tâches (regularTasks + pinnedTasks)
  const sources = useMemo((): SourceOption[] => {
    const allTasks = [...regularTasks, ...pinnedTasks];
    const hasJiraTasks = allTasks.some((task) => task.source === 'jira');
    const hasTfsTasks = allTasks.some((task) => task.source === 'tfs');
    const hasManualTasks = allTasks.some((task) => task.source === 'manual');

    return [
      {
        id: 'jira' as const,
        label: 'Jira',
        icon: <Circle size={14} />,
        hasTasks: hasJiraTasks,
      },
      {
        id: 'tfs' as const,
        label: 'TFS',
        icon: <Square size={14} />,
        hasTasks: hasTfsTasks,
      },
      {
        id: 'manual' as const,
        label: 'Manuel',
        icon: <Hand size={14} />,
        hasTasks: hasManualTasks,
      },
    ].filter((source) => source.hasTasks);
  }, [regularTasks, pinnedTasks]);

  // Si aucune source disponible, on n'affiche rien
  if (sources.length === 0) {
    return null;
  }

  // Déterminer le mode d'utilisation (Kanban ou Dashboard)
  const isKanbanMode = filters && onFiltersChange;
  const isDashboardMode =
    selectedSources &&
    onSourcesChange &&
    hiddenSources &&
    onHiddenSourcesChange;

  // Déterminer l'état actuel de chaque source
  const getSourceMode = (sourceId: 'jira' | 'tfs' | 'manual'): FilterMode => {
    if (isKanbanMode && filters) {
      if (sourceId === 'jira') {
        return filters.showJiraOnly
          ? 'show'
          : filters.hideJiraTasks
            ? 'hide'
            : 'all';
      } else if (sourceId === 'tfs') {
        return filters.showTfsOnly
          ? 'show'
          : filters.hideTfsTasks
            ? 'hide'
            : 'all';
      } else {
        // manual
        return filters.showManualOnly
          ? 'show'
          : filters.hideManualTasks
            ? 'hide'
            : 'all';
      }
    } else if (isDashboardMode && selectedSources && hiddenSources) {
      if (selectedSources.includes(sourceId)) {
        return 'show';
      } else if (hiddenSources.includes(sourceId)) {
        return 'hide';
      } else {
        return 'all';
      }
    }
    return 'all';
  };

  const handleModeChange = (
    sourceId: 'jira' | 'tfs' | 'manual',
    mode: FilterMode
  ) => {
    if (isKanbanMode && filters && onFiltersChange) {
      const updates: Partial<KanbanFilters> = {};

      if (sourceId === 'jira') {
        updates.showJiraOnly = mode === 'show';
        updates.hideJiraTasks = mode === 'hide';
      } else if (sourceId === 'tfs') {
        updates.showTfsOnly = mode === 'show';
        updates.hideTfsTasks = mode === 'hide';
      } else if (sourceId === 'manual') {
        updates.showManualOnly = mode === 'show';
        updates.hideManualTasks = mode === 'hide';
      }

      onFiltersChange({ ...filters, ...updates });
    } else if (
      isDashboardMode &&
      onSourcesChange &&
      onHiddenSourcesChange &&
      selectedSources &&
      hiddenSources
    ) {
      let newSelectedSources = [...selectedSources];
      let newHiddenSources = [...hiddenSources];

      if (mode === 'show') {
        // Ajouter à selectedSources et retirer de hiddenSources
        if (!newSelectedSources.includes(sourceId)) {
          newSelectedSources.push(sourceId);
        }
        newHiddenSources = newHiddenSources.filter((id) => id !== sourceId);
      } else if (mode === 'hide') {
        // Ajouter à hiddenSources et retirer de selectedSources
        if (!newHiddenSources.includes(sourceId)) {
          newHiddenSources.push(sourceId);
        }
        newSelectedSources = newSelectedSources.filter((id) => id !== sourceId);
      } else {
        // 'all'
        // Retirer des deux listes
        newSelectedSources = newSelectedSources.filter((id) => id !== sourceId);
        newHiddenSources = newHiddenSources.filter((id) => id !== sourceId);
      }

      onHiddenSourcesChange(newHiddenSources);
      onSourcesChange(newSelectedSources);
    }
  };

  // Déterminer la variante du bouton principal
  const getMainButtonVariant = () => {
    const activeFilters = sources.filter((source) => {
      const mode = getSourceMode(source.id);
      return mode !== 'all';
    });

    return activeFilters.length === 0 ? 'secondary' : 'selected';
  };

  const getMainButtonText = () => {
    const activeFilters = sources.filter((source) => {
      const mode = getSourceMode(source.id);
      return mode !== 'all';
    });

    if (activeFilters.length === 0) {
      return 'Sources';
    } else if (activeFilters.length === 1) {
      const source = activeFilters[0];
      const mode = getSourceMode(source.id);
      return mode === 'show' ? `Solo ${source.label}` : `-${source.label}`;
    } else {
      return `+${activeFilters.length}`;
    }
  };

  const dropdownContent = (
    <div className="space-y-3">
      {sources.map((source) => {
        const currentMode = getSourceMode(source.id);

        return (
          <div key={source.id} className="space-y-2">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm font-medium">
                <span>{source.icon}</span>
                <span>{source.label}</span>
              </div>

              <div className="flex items-center gap-1">
                {/* Bouton Afficher */}
                <button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleModeChange(source.id, 'show');
                  }}
                  onMouseDown={(e) => e.preventDefault()}
                  className={`px-2 py-1 text-xs rounded transition-colors cursor-pointer ${
                    currentMode === 'show'
                      ? 'bg-[var(--primary)] text-[var(--primary-foreground)]'
                      : 'bg-[var(--muted)] text-[var(--muted-foreground)] hover:bg-[var(--primary)]/20'
                  }`}
                  title="Afficher seulement cette source"
                >
                  ✓
                </button>

                {/* Bouton Masquer */}
                <button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleModeChange(source.id, 'hide');
                  }}
                  onMouseDown={(e) => e.preventDefault()}
                  className={`px-2 py-1 text-xs rounded transition-colors cursor-pointer ${
                    currentMode === 'hide'
                      ? 'bg-[var(--destructive)] text-white'
                      : 'bg-[var(--muted)] text-[var(--muted-foreground)] hover:bg-[var(--destructive)]/20'
                  }`}
                  title="Masquer cette source"
                >
                  ✕
                </button>
              </div>
            </div>
          </div>
        );
      })}

      {/* Option pour réinitialiser tous les filtres */}
      <div className="border-t border-[var(--border)] pt-2 mt-2">
        <Button
          variant="secondary"
          size="sm"
          onClick={() => {
            if (isKanbanMode && filters && onFiltersChange) {
              const updates: Partial<KanbanFilters> = {
                showJiraOnly: false,
                hideJiraTasks: false,
                showTfsOnly: false,
                hideTfsTasks: false,
                showManualOnly: false,
                hideManualTasks: false,
              };
              onFiltersChange({ ...filters, ...updates });
            } else if (
              isDashboardMode &&
              onHiddenSourcesChange &&
              onSourcesChange
            ) {
              onHiddenSourcesChange([]);
              onSourcesChange([]);
            }
          }}
          className="w-full justify-start font-mono"
          title="Réinitialiser tous les filtres de source"
        >
          <span>🔄&nbsp;</span>
          <span className="flex-1">Réinitialiser tout</span>
        </Button>
      </div>
    </div>
  );

  return (
    <Dropdown
      open={isOpen}
      onOpenChange={setIsOpen}
      trigger={
        <span className="flex items-center gap-1">
          <Link className="w-4 h-4" />
          {getMainButtonText()}
        </span>
      }
      variant={getMainButtonVariant()}
      content={dropdownContent}
      placement={alignRight ? 'bottom-end' : 'bottom-start'}
      className={`min-w-[239px] max-h-[190px] overflow-y-auto ${alignRight ? 'transform -translate-x-full' : ''}`}
      triggerClassName="h-[33px] py-1 max-w-[140px] truncate"
    />
  );
}
