import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, X, Filter, ChevronDown } from 'lucide-react';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import { Input } from '../../ui/Input';
import type { AlertSeverity, AlertCategory, TimeGroup } from '../../../utils/alertHelpers';
import { getCategoryName, getCategoryIcon } from '../../../utils/alertHelpers';

export interface AlertFiltersProps {
  selectedSeverities: AlertSeverity[];
  selectedCategories: AlertCategory[];
  selectedTimeRange: TimeGroup | 'all';
  searchQuery: string;
  showSnoozed: boolean;
  onToggleSeverity: (severity: AlertSeverity) => void;
  onToggleCategory: (category: AlertCategory) => void;
  onSetTimeRange: (range: TimeGroup | 'all') => void;
  onSearchChange: (query: string) => void;
  onToggleShowSnoozed: () => void;
  onClearFilters: () => void;
  hasActiveFilters: boolean;
  activeFilterCount: number;
}

const SEVERITY_CONFIG: Record<AlertSeverity, { label: string; color: string; variant: 'error' | 'warning' | 'info' | 'success' }> = {
  urgent: { label: 'Urgente', color: 'bg-red-500', variant: 'error' },
  high: { label: 'Alta', color: 'bg-orange-500', variant: 'warning' },
  medium: { label: 'Media', color: 'bg-blue-500', variant: 'info' },
  low: { label: 'Baja', color: 'bg-green-500', variant: 'success' },
};

const TIME_RANGES: Array<{ value: TimeGroup | 'all'; label: string }> = [
  { value: 'all', label: 'Todos' },
  { value: 'today', label: 'Hoy' },
  { value: 'yesterday', label: 'Ayer' },
  { value: 'this_week', label: 'Esta semana' },
  { value: 'older', label: 'Anteriores' },
];

const CATEGORIES: AlertCategory[] = ['inventory', 'production', 'orders', 'equipment', 'quality', 'suppliers'];

const AlertFilters: React.FC<AlertFiltersProps> = ({
  selectedSeverities,
  selectedCategories,
  selectedTimeRange,
  searchQuery,
  showSnoozed,
  onToggleSeverity,
  onToggleCategory,
  onSetTimeRange,
  onSearchChange,
  onToggleShowSnoozed,
  onClearFilters,
  hasActiveFilters,
  activeFilterCount,
}) => {
  const { t, i18n } = useTranslation(['dashboard']);
  // Start collapsed by default for cleaner UI
  const [showFilters, setShowFilters] = useState(false);

  return (
    <div className="space-y-3">
      {/* Search and Filter Toggle */}
      <div className="flex items-center gap-2">
        <div className="flex-1 relative">
          <Input
            type="text"
            placeholder={t('dashboard:alerts.filters.search_placeholder', 'Buscar alertas...')}
            value={searchQuery}
            onChange={(e) => onSearchChange(e.target.value)}
            leftIcon={<Search className="w-4 h-4" />}
            rightIcon={
              searchQuery ? (
                <button
                  onClick={() => onSearchChange('')}
                  className="p-1 hover:bg-[var(--bg-secondary)] rounded-full transition-colors"
                  aria-label="Clear search"
                >
                  <X className="w-3 h-3" />
                </button>
              ) : undefined
            }
            className="pr-8 h-10"
          />
        </div>

        <Button
          variant={showFilters || hasActiveFilters ? 'primary' : 'outline'}
          size="md"
          onClick={() => setShowFilters(!showFilters)}
          className="flex items-center gap-2 relative h-10 px-4"
          aria-expanded={showFilters}
          aria-label="Toggle filters"
        >
          <Filter className="w-4 h-4" />
          <span className="hidden sm:inline font-medium">Filtros</span>
          {activeFilterCount > 0 && (
            <span className="absolute -top-1.5 -right-1.5 w-5 h-5 bg-[var(--color-error)] text-white text-xs font-bold rounded-full flex items-center justify-center">
              {activeFilterCount}
            </span>
          )}
          <ChevronDown className={`w-4 h-4 transition-transform duration-200 ${showFilters ? 'rotate-180' : ''}`} />
        </Button>

        {hasActiveFilters && (
          <Button
            variant="ghost"
            size="sm"
            onClick={onClearFilters}
            className="text-red-500 hover:text-red-600 h-10 px-3"
            title="Clear all filters"
            aria-label="Clear all filters"
          >
            <X className="w-4 h-4" />
            <span className="sr-only">Limpiar filtros</span>
          </Button>
        )}
      </div>

      {/* Expandable Filters Panel - Animated */}
      {showFilters && (
        <div className="p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] space-y-5 animate-in fade-in slide-in-from-top-2 duration-200">
          {/* Severity Filters */}
          <div>
            <label className="block text-sm font-semibold text-[var(--text-primary)] mb-3">
              {t('dashboard:alerts.filters.severity', 'Severidad')}
            </label>
            <div className="flex flex-wrap gap-2">
              {(Object.keys(SEVERITY_CONFIG) as AlertSeverity[]).map((severity) => {
                const config = SEVERITY_CONFIG[severity];
                const isSelected = selectedSeverities.includes(severity);

                return (
                  <button
                    key={severity}
                    onClick={() => onToggleSeverity(severity)}
                    className={`
                      px-4 py-2 rounded-lg text-sm font-medium transition-all
                      ${isSelected
                        ? 'ring-2 ring-[var(--color-primary)] ring-offset-2 ring-offset-[var(--bg-secondary)] scale-105'
                        : 'opacity-70 hover:opacity-100 hover:scale-105'
                      }
                    `}
                    aria-pressed={isSelected}
                  >
                    <Badge variant={config.variant} size="sm" className="pointer-events-none">
                      {config.label}
                    </Badge>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Category Filters */}
          <div>
            <label className="block text-sm font-semibold text-[var(--text-primary)] mb-3">
              {t('dashboard:alerts.filters.category', 'Categoría')}
            </label>
            <div className="flex flex-wrap gap-2">
              {CATEGORIES.map((category) => {
                const isSelected = selectedCategories.includes(category);

                return (
                  <button
                    key={category}
                    onClick={() => onToggleCategory(category)}
                    className={`
                      px-4 py-2 rounded-lg text-sm font-medium transition-all border-2
                      ${isSelected
                        ? 'bg-[var(--color-primary)] text-white border-[var(--color-primary)] scale-105'
                        : 'bg-[var(--bg-primary)] text-[var(--text-secondary)] border-[var(--border-primary)] hover:border-[var(--color-primary)] hover:text-[var(--text-primary)] hover:scale-105'
                      }
                    `}
                    aria-pressed={isSelected}
                  >
                    <span className="mr-1.5">{getCategoryIcon(category)}</span>
                    {getCategoryName(category, i18n.language)}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Time Range Filters */}
          <div>
            <label className="block text-sm font-semibold text-[var(--text-primary)] mb-3">
              {t('dashboard:alerts.filters.time_range', 'Periodo')}
            </label>
            <div className="grid grid-cols-3 sm:grid-cols-5 gap-2">
              {TIME_RANGES.map((range) => {
                const isSelected = selectedTimeRange === range.value;

                return (
                  <button
                    key={range.value}
                    onClick={() => onSetTimeRange(range.value)}
                    className={`
                      px-4 py-2 rounded-lg text-sm font-medium transition-all
                      ${isSelected
                        ? 'bg-[var(--color-primary)] text-white shadow-md scale-105'
                        : 'bg-[var(--bg-primary)] text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-primary)] hover:scale-105'
                      }
                    `}
                    aria-pressed={isSelected}
                  >
                    {range.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Show Snoozed Toggle */}
          <div className="flex items-center justify-between pt-3 border-t border-[var(--border-primary)]">
            <label htmlFor="show-snoozed-toggle" className="text-sm font-medium text-[var(--text-primary)] cursor-pointer">
              {t('dashboard:alerts.filters.show_snoozed', 'Mostrar pospuestos')}
            </label>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                id="show-snoozed-toggle"
                type="checkbox"
                checked={showSnoozed}
                onChange={onToggleShowSnoozed}
                className="sr-only peer"
                aria-label="Toggle show snoozed alerts"
              />
              <div className="w-11 h-6 bg-gray-300 dark:bg-gray-600 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[var(--color-primary)]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--color-primary)]"></div>
            </label>
          </div>
        </div>
      )}

      {/* Active Filters Summary - Chips */}
      {hasActiveFilters && !showFilters && (
        <div className="flex flex-wrap gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
          <span className="text-xs font-medium text-[var(--text-secondary)] self-center">
            Filtros activos:
          </span>

          {selectedSeverities.map((severity) => (
            <button
              key={severity}
              onClick={() => onToggleSeverity(severity)}
              className="group inline-flex items-center gap-1.5 transition-all hover:scale-105"
              aria-label={`Remove ${severity} filter`}
            >
              <Badge
                variant={SEVERITY_CONFIG[severity].variant}
                size="sm"
                className="flex items-center gap-1.5 pr-1"
              >
                {SEVERITY_CONFIG[severity].label}
                <span className="p-0.5 rounded-full hover:bg-black/10 transition-colors">
                  <X className="w-3 h-3" />
                </span>
              </Badge>
            </button>
          ))}

          {selectedCategories.map((category) => (
            <button
              key={category}
              onClick={() => onToggleCategory(category)}
              className="group inline-flex items-center gap-1.5 transition-all hover:scale-105"
              aria-label={`Remove ${category} filter`}
            >
              <Badge
                variant="secondary"
                size="sm"
                className="flex items-center gap-1.5 pr-1"
              >
                {getCategoryIcon(category)} {getCategoryName(category, i18n.language)}
                <span className="p-0.5 rounded-full hover:bg-black/10 transition-colors">
                  <X className="w-3 h-3" />
                </span>
              </Badge>
            </button>
          ))}

          {selectedTimeRange !== 'all' && (
            <button
              onClick={() => onSetTimeRange('all')}
              className="group inline-flex items-center gap-1.5 transition-all hover:scale-105"
              aria-label="Remove time range filter"
            >
              <Badge
                variant="info"
                size="sm"
                className="flex items-center gap-1.5 pr-1"
              >
                {TIME_RANGES.find(r => r.value === selectedTimeRange)?.label}
                <span className="p-0.5 rounded-full hover:bg-black/10 transition-colors">
                  <X className="w-3 h-3" />
                </span>
              </Badge>
            </button>
          )}
        </div>
      )}
    </div>
  );
};

export default AlertFilters;
