import React from 'react';
import { useTranslation } from 'react-i18next';
import { Brain, TrendingUp, AlertTriangle, Target, Zap, DollarSign, Clock } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { Badge, Button } from '../../../../ui';
import { useCurrentTenant } from '../../../../../stores/tenant.store';
import { useTenantCurrency } from '../../../../../hooks/useTenantCurrency';

interface AIInsight {
  id: string;
  type: 'optimization' | 'prediction' | 'anomaly' | 'recommendation';
  priority: 'low' | 'medium' | 'high' | 'critical';
  confidence: number; // percentage
  title: string;
  description: string;
  impact: {
    type: 'cost_savings' | 'efficiency_gain' | 'quality_improvement' | 'risk_mitigation';
    value: number;
    unit: 'euros' | 'percentage' | 'hours' | 'units';
  };
  actionable: boolean;
  category: 'production' | 'quality' | 'maintenance' | 'energy' | 'scheduling';
  equipment?: string;
  timeline: string;
  status: 'new' | 'acknowledged' | 'in_progress' | 'implemented' | 'dismissed';
}

export const AIInsightsWidget: React.FC = () => {
  const { t } = useTranslation('production');
  const currentTenant = useCurrentTenant();
  const { currencySymbol } = useTenantCurrency();

  // Mock AI insights data - replace with real AI API call
  const aiInsights: AIInsight[] = [
    {
      id: '1',
      type: 'optimization',
      priority: 'high',
      confidence: 92,
      title: 'Optimización de Horarios de Horneado',
      description: 'Ajustar los horarios de horneado para aprovechar las tarifas eléctricas más bajas puede reducir los costos de energía en un 15%.',
      impact: {
        type: 'cost_savings',
        value: 45,
        unit: 'euros'
      },
      actionable: true,
      category: 'energy',
      equipment: 'Horno Principal',
      timeline: 'Esta semana',
      status: 'new'
    },
    {
      id: '2',
      type: 'prediction',
      priority: 'medium',
      confidence: 87,
      title: 'Aumento de Demanda de Croissants Predicho',
      description: 'Los datos meteorológicos y de eventos sugieren un aumento del 40% en la demanda de croissants este fin de semana.',
      impact: {
        type: 'efficiency_gain',
        value: 25,
        unit: 'percentage'
      },
      actionable: true,
      category: 'production',
      timeline: 'Este fin de semana',
      status: 'acknowledged'
    },
    {
      id: '3',
      type: 'anomaly',
      priority: 'critical',
      confidence: 96,
      title: 'Declive en Puntuación de Calidad Detectado',
      description: 'La calidad del pan ha disminuido un 8% en los últimos 3 días. Verificar los niveles de humedad de la harina.',
      impact: {
        type: 'quality_improvement',
        value: 12,
        unit: 'percentage'
      },
      actionable: true,
      category: 'quality',
      timeline: 'Inmediatamente',
      status: 'in_progress'
    },
    {
      id: '4',
      type: 'recommendation',
      priority: 'medium',
      confidence: 89,
      title: 'Mantenimiento Preventivo Recomendado',
      description: 'La Mezcladora #2 muestra patrones de desgaste temprano. Programar mantenimiento para prevenir averías.',
      impact: {
        type: 'risk_mitigation',
        value: 8,
        unit: 'hours'
      },
      actionable: true,
      category: 'maintenance',
      equipment: 'Mezcladora A',
      timeline: 'Próxima semana',
      status: 'new'
    },
    {
      id: '5',
      type: 'optimization',
      priority: 'low',
      confidence: 78,
      title: 'Optimización de Secuencia de Productos',
      description: 'Reordenar la secuencia de productos puede mejorar la eficiencia general en un 5%.',
      impact: {
        type: 'efficiency_gain',
        value: 5,
        unit: 'percentage'
      },
      actionable: true,
      category: 'scheduling',
      timeline: 'Próximo mes',
      status: 'dismissed'
    }
  ];

  const getTypeIcon = (type: AIInsight['type']) => {
    switch (type) {
      case 'optimization': return Target;
      case 'prediction': return TrendingUp;
      case 'anomaly': return AlertTriangle;
      case 'recommendation': return Brain;
      default: return Brain;
    }
  };

  const getTypeColor = (type: AIInsight['type']) => {
    switch (type) {
      case 'optimization': return 'text-[var(--color-success)]';
      case 'prediction': return 'text-[var(--color-info)]';
      case 'anomaly': return 'text-[var(--color-error)]';
      case 'recommendation': return 'text-[var(--color-secondary)]';
      default: return 'text-[var(--text-secondary)]';
    }
  };

  const getPriorityBadgeVariant = (priority: AIInsight['priority']) => {
    switch (priority) {
      case 'critical': return 'error';
      case 'high': return 'warning';
      case 'medium': return 'info';
      case 'low': return 'default';
      default: return 'default';
    }
  };

  const getStatusBadgeVariant = (status: AIInsight['status']) => {
    switch (status) {
      case 'new': return 'warning';
      case 'acknowledged': return 'info';
      case 'in_progress': return 'info';
      case 'implemented': return 'success';
      case 'dismissed': return 'default';
      default: return 'default';
    }
  };

  const getImpactIcon = (type: AIInsight['impact']['type']) => {
    switch (type) {
      case 'cost_savings': return DollarSign;
      case 'efficiency_gain': return Zap;
      case 'quality_improvement': return Target;
      case 'risk_mitigation': return Clock;
      default: return Target;
    }
  };

  const formatImpactValue = (impact: AIInsight['impact']) => {
    switch (impact.unit) {
      case 'euros': return `${currencySymbol}${impact.value}`;
      case 'percentage': return `${impact.value}%`;
      case 'hours': return `${impact.value}h`;
      case 'units': return `${impact.value} unidades`;
      default: return impact.value.toString();
    }
  };

  const activeInsights = aiInsights.filter(i => i.status !== 'dismissed');
  const highPriorityInsights = activeInsights.filter(i => i.priority === 'high' || i.priority === 'critical');
  const implementedInsights = aiInsights.filter(i => i.status === 'implemented');
  const avgConfidence = activeInsights.reduce((sum, insight) => sum + insight.confidence, 0) / activeInsights.length;

  const totalPotentialSavings = aiInsights
    .filter(i => i.impact.type === 'cost_savings' && i.status !== 'dismissed')
    .reduce((sum, insight) => sum + insight.impact.value, 0);

  return (
    <AnalyticsWidget
      title={t('ai.title')}
      subtitle={t('ai.subtitle')}
      icon={Brain}
      actions={
        <div className="flex space-x-2">
          <Button variant="outline" size="sm">
            <Brain className="w-4 h-4 mr-1" />
            {t('ai.actions.train_model')}
          </Button>
          <Button variant="primary" size="sm">
            <Target className="w-4 h-4 mr-1" />
            {t('ai.actions.implement_all')}
          </Button>
        </div>
      }
    >
      <div className="space-y-5">
        {/* AI Insights Overview Stats */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] hover:border-[var(--border-focus)] transition-colors">
            <Brain className="w-8 h-8 mx-auto text-[var(--color-secondary)] mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{activeInsights.length}</p>
            <p className="text-sm text-[var(--text-secondary)] font-medium">{t('ai.stats.active_insights')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--color-error)]/10 rounded-lg border border-[var(--color-error)]/20 hover:border-[var(--color-error)]/40 transition-colors">
            <AlertTriangle className="w-8 h-8 mx-auto text-[var(--color-error)] mb-2" />
            <p className="text-2xl font-bold text-[var(--color-error)]">{highPriorityInsights.length}</p>
            <p className="text-sm text-[var(--text-secondary)] font-medium">{t('ai.stats.high_priority')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--color-success)]/10 rounded-lg border border-[var(--color-success)]/20 hover:border-[var(--color-success)]/40 transition-colors">
            <div className="w-8 h-8 mx-auto bg-[var(--color-success)]/20 rounded-full flex items-center justify-center mb-2">
              <span className="text-[var(--color-success)] font-bold text-sm">{currencySymbol}</span>
            </div>
            <p className="text-2xl font-bold text-[var(--color-success)]">{currencySymbol}{totalPotentialSavings}</p>
            <p className="text-sm text-[var(--text-secondary)] font-medium">{t('ai.stats.potential_savings')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--color-info)]/10 rounded-lg border border-[var(--color-info)]/20 hover:border-[var(--color-info)]/40 transition-colors">
            <div className="w-8 h-8 mx-auto bg-[var(--color-info)]/20 rounded-full flex items-center justify-center mb-2">
              <span className="text-[var(--color-info)] font-bold text-sm">%</span>
            </div>
            <p className="text-2xl font-bold text-[var(--color-info)]">{avgConfidence.toFixed(0)}%</p>
            <p className="text-sm text-[var(--text-secondary)] font-medium">{t('ai.stats.avg_confidence')}</p>
          </div>
        </div>

        {/* AI Status */}
        <div className="p-4 bg-[var(--color-success)]/10 border border-[var(--color-success)]/20 rounded-lg">
          <div className="flex items-center space-x-2">
            <div className="w-2 h-2 bg-[var(--color-success)] rounded-full animate-pulse"></div>
            <span className="text-sm font-semibold text-[var(--color-success)]">
              {t('ai.status.active')}
            </span>
            <span className="text-xs text-[var(--text-secondary)] ml-2 font-medium">
              {t('ai.last_updated')}
            </span>
          </div>
        </div>

        {/* High Priority Insights */}
        {highPriorityInsights.length > 0 && (
          <div>
            <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center">
              <AlertTriangle className="w-4 h-4 mr-2 text-[var(--color-error)]" />
              {t('ai.high_priority_insights')} ({highPriorityInsights.length})
            </h4>
            <div className="space-y-3">
              {highPriorityInsights.slice(0, 3).map((insight) => {
                const TypeIcon = getTypeIcon(insight.type);
                const ImpactIcon = getImpactIcon(insight.impact.type);

                return (
                  <div key={insight.id} className="p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--color-error)]/30 hover:border-[var(--color-error)]/50 transition-all duration-200">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-start space-x-3">
                        <TypeIcon className={`w-5 h-5 mt-1 ${getTypeColor(insight.type)}`} />
                        <div className="flex-1">
                          <div className="flex items-center space-x-2 mb-1">
                            <p className="font-medium text-[var(--text-primary)]">{insight.title}</p>
                            <Badge variant={getPriorityBadgeVariant(insight.priority)}>
                              {t(`ai.priority.${insight.priority}`)}
                            </Badge>
                          </div>
                          <p className="text-sm text-[var(--text-secondary)] mb-2">{insight.description}</p>
                          <div className="flex items-center space-x-4 text-xs text-[var(--text-secondary)]">
                            <span>{t('ai.confidence')}: {insight.confidence}%</span>
                            <span>{t('ai.timeline')}: {insight.timeline}</span>
                            {insight.equipment && <span>{t('ai.equipment')}: {insight.equipment}</span>}
                          </div>
                        </div>
                      </div>
                      <Badge variant={getStatusBadgeVariant(insight.status)}>
                        {t(`ai.status.${insight.status}`)}
                      </Badge>
                    </div>

                    {/* Impact */}
                    <div className="flex items-center justify-between p-3 bg-[var(--color-success)]/5 border border-[var(--color-success)]/10 rounded-lg">
                      <div className="flex items-center space-x-2">
                        <ImpactIcon className="w-4 h-4 text-[var(--color-primary)]" />
                        <span className="text-sm font-semibold text-[var(--text-primary)]">
                          {t(`ai.impact.${insight.impact.type}`)}
                        </span>
                      </div>
                      <span className="text-lg font-bold text-[var(--color-success)]">
                        {formatImpactValue(insight.impact)}
                      </span>
                    </div>

                    {insight.actionable && insight.status === 'new' && (
                      <div className="mt-3 flex space-x-2">
                        <Button variant="outline" size="sm">
                          {t('ai.actions.acknowledge')}
                        </Button>
                        <Button variant="primary" size="sm">
                          {t('ai.actions.implement')}
                        </Button>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* All Insights */}
        <div>
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center">
            <Brain className="w-4 h-4 mr-2 text-[var(--color-secondary)]" />
            {t('ai.all_insights')} ({activeInsights.length})
          </h4>
          <div className="space-y-2 max-h-96 overflow-y-auto pr-1">
            {activeInsights.map((insight) => {
              const TypeIcon = getTypeIcon(insight.type);
              const ImpactIcon = getImpactIcon(insight.impact.type);

              return (
                <div key={insight.id} className="p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] hover:border-[var(--border-focus)] hover:shadow-sm transition-all duration-200">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <TypeIcon className={`w-4 h-4 ${getTypeColor(insight.type)}`} />
                      <div className="flex-1">
                        <div className="flex items-center space-x-2">
                          <p className="font-medium text-[var(--text-primary)] text-sm">{insight.title}</p>
                          <Badge variant={getPriorityBadgeVariant(insight.priority)} className="text-xs">
                            {t(`ai.priority.${insight.priority}`)}
                          </Badge>
                        </div>
                        <div className="flex items-center space-x-4 text-xs text-[var(--text-secondary)] mt-1">
                          <span>{insight.confidence}% {t('ai.confidence')}</span>
                          <span>•</span>
                          <span>{insight.timeline}</span>
                          <span>•</span>
                          <div className="flex items-center space-x-1">
                            <ImpactIcon className="w-3 h-3" />
                            <span>{formatImpactValue(insight.impact)}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <Badge variant={getStatusBadgeVariant(insight.status)} className="text-xs">
                      {t(`ai.status.${insight.status}`)}
                    </Badge>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* AI Performance Summary */}
        <div className="p-4 bg-[var(--color-info)]/10 border border-[var(--color-info)]/20 rounded-lg">
          <div className="flex items-start space-x-3">
            <Brain className="w-5 h-5 text-[var(--color-info)] mt-0.5" />
            <div className="flex-1">
              <p className="text-sm font-semibold text-[var(--color-info)] mb-1">
                {t('ai.performance.summary')}
              </p>
              <p className="text-xs text-[var(--text-secondary)]">
                {implementedInsights.length} {t('ai.performance.insights_implemented')}
                {totalPotentialSavings > 0 && `, ${currencySymbol}${totalPotentialSavings} ${t('ai.performance.in_savings_identified')}`}
              </p>
            </div>
          </div>
        </div>
      </div>
    </AnalyticsWidget>
  );
};