'use client';

import { useState, useEffect } from 'react';
import { JiraAnalyticsFilters, AvailableFilters } from '@/lib/types';
import { JiraAdvancedFiltersService } from '@/services/integrations/jira/advanced-filters';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { Modal } from '@/components/ui/Modal';
import { Emoji } from '@/components/ui/Emoji';

interface FilterBarProps {
  availableFilters: AvailableFilters;
  activeFilters: Partial<JiraAnalyticsFilters>;
  onFiltersChange: (filters: Partial<JiraAnalyticsFilters>) => void;
  isLoading?: boolean;
  className?: string;
}

export default function FilterBar({
  availableFilters,
  activeFilters,
  onFiltersChange,
  isLoading = false,
  className = '',
}: FilterBarProps) {
  const [showModal, setShowModal] = useState(false);
  const [pendingFilters, setPendingFilters] =
    useState<Partial<JiraAnalyticsFilters>>(activeFilters);

  const hasActiveFilters =
    JiraAdvancedFiltersService.hasActiveFilters(activeFilters);
  const activeFiltersCount =
    JiraAdvancedFiltersService.countActiveFilters(activeFilters);

  const clearAllFilters = () => {
    const emptyFilters = JiraAdvancedFiltersService.createEmptyFilters();
    setPendingFilters(emptyFilters);
  };

  const applyPendingFilters = () => {
    onFiltersChange(pendingFilters);
    setShowModal(false);
  };

  const cancelFilters = () => {
    setPendingFilters(activeFilters);
    setShowModal(false);
  };

  // Synchroniser pendingFilters avec activeFilters quand ils changent
  useEffect(() => {
    setPendingFilters(activeFilters);
  }, [activeFilters]);

  const removeFilter = (
    filterType: keyof JiraAnalyticsFilters,
    value: string
  ) => {
    const currentValues = activeFilters[filterType];
    if (!currentValues || !Array.isArray(currentValues)) return;

    const newValues = currentValues.filter((v: string) => v !== value);
    onFiltersChange({
      ...activeFilters,
      [filterType]: newValues,
    });
  };

  return (
    <div
      className={`bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 ${className}`}
    >
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-[var(--foreground)]">
              <Emoji emoji="🔍" /> Filtres
            </span>
            {isLoading && (
              <Badge className="bg-yellow-100 text-yellow-800 text-xs">
                <Emoji emoji="⏳" /> Chargement...
              </Badge>
            )}
            {hasActiveFilters && !isLoading && (
              <Badge className="bg-blue-100 text-blue-800 text-xs">
                {activeFiltersCount}
              </Badge>
            )}
          </div>

          {/* Filtres actifs */}
          {hasActiveFilters && (
            <div className="flex flex-wrap gap-1 max-w-2xl overflow-hidden">
              {activeFilters.components?.slice(0, 3).map((comp) => (
                <Badge
                  key={comp}
                  className="bg-purple-100 text-purple-800 text-xs cursor-pointer hover:bg-purple-200 transition-colors"
                  onClick={() => removeFilter('components', comp)}
                >
                  <Emoji emoji="📦" /> {comp} ×
                </Badge>
              ))}
              {activeFilters.fixVersions?.slice(0, 2).map((version) => (
                <Badge
                  key={version}
                  className="bg-green-100 text-green-800 text-xs cursor-pointer hover:bg-green-200 transition-colors"
                  onClick={() => removeFilter('fixVersions', version)}
                >
                  <Emoji emoji="🏷️" /> {version} ×
                </Badge>
              ))}
              {activeFilters.issueTypes?.slice(0, 3).map((type) => (
                <Badge
                  key={type}
                  className="bg-orange-100 text-orange-800 text-xs cursor-pointer hover:bg-orange-200 transition-colors"
                  onClick={() => removeFilter('issueTypes', type)}
                >
                  <Emoji emoji="📋" /> {type} ×
                </Badge>
              ))}
              {activeFilters.statuses?.slice(0, 2).map((status) => (
                <Badge
                  key={status}
                  className="bg-blue-100 text-blue-800 text-xs cursor-pointer hover:bg-blue-200 transition-colors"
                  onClick={() => removeFilter('statuses', status)}
                >
                  <Emoji emoji="🔄" /> {status} ×
                </Badge>
              ))}
              {activeFilters.assignees?.slice(0, 2).map((assignee) => (
                <Badge
                  key={assignee}
                  className="bg-yellow-100 text-yellow-800 text-xs cursor-pointer hover:bg-yellow-200 transition-colors"
                  onClick={() => removeFilter('assignees', assignee)}
                >
                  <Emoji emoji="👤" /> {assignee} ×
                </Badge>
              ))}

              {/* Indicateur si plus de filtres */}
              {(() => {
                const totalVisible =
                  (activeFilters.components?.slice(0, 3).length || 0) +
                  (activeFilters.fixVersions?.slice(0, 2).length || 0) +
                  (activeFilters.issueTypes?.slice(0, 3).length || 0) +
                  (activeFilters.statuses?.slice(0, 2).length || 0) +
                  (activeFilters.assignees?.slice(0, 2).length || 0);

                const totalActive = activeFiltersCount;

                if (totalActive > totalVisible) {
                  return (
                    <Badge className="bg-gray-100 text-gray-800 text-xs">
                      +{totalActive - totalVisible} autres
                    </Badge>
                  );
                }
                return null;
              })()}
            </div>
          )}

          {!hasActiveFilters && (
            <span className="text-sm text-[var(--muted-foreground)]">
              Aucun filtre actif
            </span>
          )}
        </div>

        <div className="flex items-center gap-2">
          {hasActiveFilters && (
            <Button
              onClick={clearAllFilters}
              variant="secondary"
              size="sm"
              className="text-xs"
            >
              Effacer
            </Button>
          )}
          <Button
            onClick={() => setShowModal(true)}
            variant="primary"
            size="sm"
            className="text-xs"
          >
            Configurer
          </Button>
        </div>
      </div>

      {/* Modal de configuration - réutilise la logique du composant existant */}
      {showModal && (
        <Modal
          isOpen={showModal}
          onClose={() => setShowModal(false)}
          title="Configuration des filtres"
          size="lg"
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-h-96 overflow-y-auto">
            {/* Types de tickets */}
            <div>
              <h4 className="font-medium text-sm mb-3">
                <Emoji emoji="📋" /> Types de tickets
              </h4>
              <div className="space-y-1 max-h-32 overflow-y-auto">
                {availableFilters.issueTypes.map((option) => (
                  <label
                    key={option.value}
                    className="flex items-center gap-2 text-sm cursor-pointer hover:bg-[var(--muted)] px-2 py-1 rounded"
                  >
                    <input
                      type="checkbox"
                      checked={
                        pendingFilters.issueTypes?.includes(option.value) ||
                        false
                      }
                      onChange={(e) => {
                        const current = pendingFilters.issueTypes || [];
                        const newValues = e.target.checked
                          ? [...current, option.value]
                          : current.filter((v) => v !== option.value);
                        setPendingFilters({
                          ...pendingFilters,
                          issueTypes: newValues,
                        });
                      }}
                      className="rounded"
                    />
                    <span className="flex-1 truncate">{option.label}</span>
                    <span className="text-xs text-[var(--muted-foreground)]">
                      ({option.count})
                    </span>
                  </label>
                ))}
              </div>
            </div>

            {/* Statuts */}
            <div>
              <h4 className="font-medium text-sm mb-3">
                <Emoji emoji="🔄" /> Statuts
              </h4>
              <div className="space-y-1 max-h-32 overflow-y-auto">
                {availableFilters.statuses.map((option) => (
                  <label
                    key={option.value}
                    className="flex items-center gap-2 text-sm cursor-pointer hover:bg-[var(--muted)] px-2 py-1 rounded"
                  >
                    <input
                      type="checkbox"
                      checked={
                        pendingFilters.statuses?.includes(option.value) || false
                      }
                      onChange={(e) => {
                        const current = pendingFilters.statuses || [];
                        const newValues = e.target.checked
                          ? [...current, option.value]
                          : current.filter((v) => v !== option.value);
                        setPendingFilters({
                          ...pendingFilters,
                          statuses: newValues,
                        });
                      }}
                      className="rounded"
                    />
                    <span className="flex-1 truncate">{option.label}</span>
                    <span className="text-xs text-[var(--muted-foreground)]">
                      ({option.count})
                    </span>
                  </label>
                ))}
              </div>
            </div>

            {/* Assignés */}
            <div>
              <h4 className="font-medium text-sm mb-3">
                <Emoji emoji="👤" /> Assignés
              </h4>
              <div className="space-y-1 max-h-32 overflow-y-auto">
                {availableFilters.assignees.map((option) => (
                  <label
                    key={option.value}
                    className="flex items-center gap-2 text-sm cursor-pointer hover:bg-[var(--muted)] px-2 py-1 rounded"
                  >
                    <input
                      type="checkbox"
                      checked={
                        pendingFilters.assignees?.includes(option.value) ||
                        false
                      }
                      onChange={(e) => {
                        const current = pendingFilters.assignees || [];
                        const newValues = e.target.checked
                          ? [...current, option.value]
                          : current.filter((v) => v !== option.value);
                        setPendingFilters({
                          ...pendingFilters,
                          assignees: newValues,
                        });
                      }}
                      className="rounded"
                    />
                    <span className="flex-1 truncate">{option.label}</span>
                    <span className="text-xs text-[var(--muted-foreground)]">
                      ({option.count})
                    </span>
                  </label>
                ))}
              </div>
            </div>

            {/* Composants */}
            <div>
              <h4 className="font-medium text-sm mb-3">
                <Emoji emoji="📦" /> Composants
              </h4>
              <div className="space-y-1 max-h-32 overflow-y-auto">
                {availableFilters.components.map((option) => (
                  <label
                    key={option.value}
                    className="flex items-center gap-2 text-sm cursor-pointer hover:bg-[var(--muted)] px-2 py-1 rounded"
                  >
                    <input
                      type="checkbox"
                      checked={
                        pendingFilters.components?.includes(option.value) ||
                        false
                      }
                      onChange={(e) => {
                        const current = pendingFilters.components || [];
                        const newValues = e.target.checked
                          ? [...current, option.value]
                          : current.filter((v) => v !== option.value);
                        setPendingFilters({
                          ...pendingFilters,
                          components: newValues,
                        });
                      }}
                      className="rounded"
                    />
                    <span className="flex-1 truncate">{option.label}</span>
                    <span className="text-xs text-[var(--muted-foreground)]">
                      ({option.count})
                    </span>
                  </label>
                ))}
              </div>
            </div>
          </div>

          <div className="flex gap-2 pt-6 border-t">
            <Button
              onClick={cancelFilters}
              variant="secondary"
              className="flex-1"
            >
              <Emoji emoji="❌" /> Annuler
            </Button>
            <Button
              onClick={clearAllFilters}
              variant="secondary"
              className="flex-1"
            >
              <Emoji emoji="🗑️" /> Effacer tout
            </Button>
            <Button
              onClick={applyPendingFilters}
              className="flex-1"
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <Emoji emoji="⏳" /> Application...
                </>
              ) : (
                <>
                  <Emoji emoji="✅" /> Appliquer
                </>
              )}
            </Button>
          </div>
        </Modal>
      )}
    </div>
  );
}
