import React, { useState } from 'react';
import { Card, Button } from '../../ui';
import { Calendar, User, Filter as FilterIcon, X } from 'lucide-react';
import { AuditLogFilters, AuditLogStatsResponse, AUDIT_LOG_SERVICES } from '../../../api/types/auditLogs';

interface EventFilterSidebarProps {
  filters: AuditLogFilters;
  onFiltersChange: (filters: Partial<AuditLogFilters>) => void;
  stats?: AuditLogStatsResponse;
}

export const EventFilterSidebar: React.FC<EventFilterSidebarProps> = ({
  filters,
  onFiltersChange,
  stats,
}) => {
  const [localFilters, setLocalFilters] = useState<AuditLogFilters>(filters);

  const handleApply = () => {
    onFiltersChange(localFilters);
  };

  const handleClear = () => {
    const clearedFilters: AuditLogFilters = { limit: 50, offset: 0 };
    setLocalFilters(clearedFilters);
    onFiltersChange(clearedFilters);
  };

  return (
    <Card>
      <div className="p-4">
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-lg font-semibold text-gray-900">Filtros</h3>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleClear}
            icon={X}
          >
            Limpiar
          </Button>
        </div>

        <div className="space-y-6">
          {/* Date Range */}
          <div>
            <label className="mb-2 block text-sm font-medium text-gray-700">
              Rango de Fechas
            </label>
            <div className="space-y-2">
              <input
                type="date"
                value={localFilters.start_date?.split('T')[0] || ''}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, start_date: e.target.value ? new Date(e.target.value).toISOString() : undefined })
                }
                className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
                placeholder="Fecha inicio"
              />
              <input
                type="date"
                value={localFilters.end_date?.split('T')[0] || ''}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, end_date: e.target.value ? new Date(e.target.value).toISOString() : undefined })
                }
                className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
                placeholder="Fecha fin"
              />
            </div>
          </div>

          {/* Severity Filter */}
          <div>
            <label className="mb-2 block text-sm font-medium text-gray-700">
              Severidad
            </label>
            <select
              value={localFilters.severity || ''}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, severity: e.target.value as any || undefined })
              }
              className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
            >
              <option value="">Todas</option>
              <option value="low">Bajo</option>
              <option value="medium">Medio</option>
              <option value="high">Alto</option>
              <option value="critical">Crítico</option>
            </select>
          </div>

          {/* Action Filter */}
          <div>
            <label className="mb-2 block text-sm font-medium text-gray-700">
              Acción
            </label>
            <input
              type="text"
              value={localFilters.action || ''}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, action: e.target.value || undefined })
              }
              placeholder="create, update, delete..."
              className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
            />
          </div>

          {/* Resource Type Filter */}
          <div>
            <label className="mb-2 block text-sm font-medium text-gray-700">
              Tipo de Recurso
            </label>
            <input
              type="text"
              value={localFilters.resource_type || ''}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, resource_type: e.target.value || undefined })
              }
              placeholder="user, recipe, order..."
              className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
            />
          </div>

          {/* Search */}
          <div>
            <label className="mb-2 block text-sm font-medium text-gray-700">
              Buscar en Descripción
            </label>
            <input
              type="text"
              value={localFilters.search || ''}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, search: e.target.value || undefined })
              }
              placeholder="Buscar..."
              className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
            />
          </div>

          {/* Apply Button */}
          <Button
            variant="primary"
            className="w-full"
            onClick={handleApply}
            icon={FilterIcon}
          >
            Aplicar Filtros
          </Button>
        </div>

        {/* Stats Summary */}
        {stats && (
          <div className="mt-6 border-t border-gray-200 pt-4">
            <h4 className="mb-3 text-sm font-medium text-gray-700">Resumen</h4>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-600">Total Eventos:</span>
                <span className="font-semibold text-gray-900">{stats.total_events}</span>
              </div>
              {stats.events_by_severity && Object.keys(stats.events_by_severity).length > 0 && (
                <div className="flex justify-between">
                  <span className="text-gray-600">Críticos:</span>
                  <span className="font-semibold text-red-600">
                    {stats.events_by_severity.critical || 0}
                  </span>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </Card>
  );
};
