import React, { useState, useMemo, useCallback } from 'react';
import { clsx } from 'clsx';
import { Card, CardHeader, CardBody } from '../../ui';
import { Button } from '../../ui';
import { Badge } from '../../ui';
import { Select } from '../../ui';
import { Input } from '../../ui';
// Simple alert interface for component
interface SimpleAlert {
  id: string;
  type: string;
  product: string;
  message: string;
  severity: 'high' | 'medium' | 'low' | 'info';
  recommendation?: string;
}

export interface AlertsPanelProps {
  className?: string;
  title?: string;
  alerts?: SimpleAlert[];
  loading?: boolean;
  error?: string | null;
  onAlertAction?: (alertId: string, action: string) => void;
  onAlertDismiss?: (alertId: string) => void;
  showFilters?: boolean;
  compact?: boolean;
  maxItems?: number;
}

interface AlertFilter {
  severity: 'high' | 'medium' | 'low' | 'info' | 'all';
  type: string;
  product: string;
}

const SPANISH_SEVERITIES: Record<string, string> = {
  'high': 'Alta',
  'medium': 'Media',
  'low': 'Baja',
  'info': 'Info',
};

const SEVERITY_COLORS: Record<string, string> = {
  'high': 'text-[var(--color-error)] bg-red-50 border-red-200',
  'medium': 'text-yellow-600 bg-yellow-50 border-yellow-200',
  'low': 'text-[var(--color-info)] bg-[var(--color-info)]/5 border-[var(--color-info)]/20',
  'info': 'text-[var(--color-primary)] bg-blue-50 border-blue-200',
};

const SEVERITY_BADGE_VARIANTS: Record<string, 'danger' | 'warning' | 'success' | 'info'> = {
  'high': 'danger',
  'medium': 'warning', 
  'low': 'info',
  'info': 'info',
};

const ALERT_ICONS: Record<string, string> = {
  'high-demand': '📈',
  'low-demand': '📉',
  'low-confidence': '🎯',
  'weather': '🌦️',
  'default': '⚠️',
};


const AlertsPanel: React.FC<AlertsPanelProps> = ({
  className,
  title = 'Alertas y Recomendaciones',
  alerts = [],
  loading = false,
  error = null,
  onAlertAction,
  onAlertDismiss,
  showFilters = false,
  compact = false,
  maxItems,
}) => {
  const [filters, setFilters] = useState<AlertFilter>({
    severity: 'all',
    type: 'all',
    product: '',
  });

  // Filter and limit alerts
  const filteredAlerts = useMemo(() => {
    let filtered = [...alerts];

    // Filter by severity
    if (filters.severity !== 'all') {
      filtered = filtered.filter(alert => alert.severity === filters.severity);
    }

    // Filter by product
    if (filters.product) {
      filtered = filtered.filter(alert => 
        alert.product.toLowerCase().includes(filters.product.toLowerCase())
      );
    }

    // Sort by severity priority
    const severityOrder = { 'high': 3, 'medium': 2, 'low': 1, 'info': 0 };
    filtered.sort((a, b) => severityOrder[b.severity] - severityOrder[a.severity]);

    // Limit items if specified
    if (maxItems) {
      filtered = filtered.slice(0, maxItems);
    }

    return filtered;
  }, [alerts, filters, maxItems]);

  // Loading state
  if (loading) {
    return (
      <Card className={className}>
        <CardHeader>
          <h3 className="text-lg font-semibold text-text-primary">{title}</h3>
        </CardHeader>
        <CardBody>
          <div className="flex items-center justify-center h-32">
            <div className="flex items-center space-x-2">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-color-primary"></div>
              <span className="text-text-secondary">Cargando alertas...</span>
            </div>
          </div>
        </CardBody>
      </Card>
    );
  }

  // Error state
  if (error) {
    return (
      <Card className={className} variant="outlined">
        <CardHeader>
          <h3 className="text-lg font-semibold text-text-primary">{title}</h3>
        </CardHeader>
        <CardBody>
          <div className="flex items-center justify-center h-32">
            <div className="text-center">
              <div className="text-red-500 mb-2">
                <svg className="w-8 h-8 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <p className="text-text-secondary text-sm">{error}</p>
            </div>
          </div>
        </CardBody>
      </Card>
    );
  }

  return (
    <Card className={className}>
      <CardHeader>
        <div className="flex items-center justify-between flex-wrap gap-4">
          <h3 className="text-lg font-semibold text-text-primary">{title}</h3>
          <Badge variant="ghost">
            {filteredAlerts.length} alertas
          </Badge>
        </div>
      </CardHeader>

      <CardBody padding={compact ? 'sm' : 'md'}>
        {filteredAlerts.length === 0 ? (
          <div className="flex items-center justify-center h-32">
            <div className="text-center">
              <div className="text-green-500 mb-2">
                <svg className="w-8 h-8 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <p className="text-text-secondary text-sm">No hay alertas que mostrar</p>
            </div>
          </div>
        ) : (
          <div className="space-y-3">
            {filteredAlerts.map((alert) => (
              <div
                key={alert.id}
                className={clsx(
                  'rounded-lg border transition-all duration-200 p-4',
                  SEVERITY_COLORS[alert.severity]
                )}
              >
                <div className="flex items-start gap-3">
                  <div className="text-2xl">
                    {ALERT_ICONS[alert.type] || ALERT_ICONS['default']}
                  </div>

                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-2">
                      <Badge 
                        variant={SEVERITY_BADGE_VARIANTS[alert.severity]}
                        size="sm"
                      >
                        {SPANISH_SEVERITIES[alert.severity]}
                      </Badge>
                      {alert.product && (
                        <Badge variant="ghost" size="sm">
                          {alert.product}
                        </Badge>
                      )}
                    </div>

                    <p className="text-text-primary text-sm mb-2">
                      {alert.message}
                    </p>

                    {alert.recommendation && (
                      <p className="text-text-secondary text-sm mb-3">
                        💡 {alert.recommendation}
                      </p>
                    )}

                    <div className="flex items-center gap-2">
                      {onAlertAction && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => onAlertAction(alert.id, 'acknowledge')}
                        >
                          ✓ Confirmar
                        </Button>
                      )}
                      {onAlertDismiss && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => onAlertDismiss(alert.id)}
                        >
                          ✕ Descartar
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardBody>
    </Card>
  );
};

export default AlertsPanel;