import React from 'react';
import { useTranslation } from 'react-i18next';
import { Brain, AlertTriangle, TrendingDown, Calendar, Wrench, Target } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { AnalyticsChart, ChartSeries } from '../AnalyticsChart';
import { Badge, Button } from '../../../../ui';
import { useCurrentTenant } from '../../../../../stores/tenant.store';
import { useTenantCurrency } from '../../../../../hooks/useTenantCurrency';

interface PredictiveMaintenanceAlert {
  id: string;
  equipmentId: string;
  equipmentName: string;
  equipmentType: 'oven' | 'mixer' | 'proofer' | 'packaging';
  alertType: 'wear_prediction' | 'failure_risk' | 'performance_degradation' | 'component_replacement';
  severity: 'low' | 'medium' | 'high' | 'critical';
  confidence: number; // percentage
  predictedFailureDate: string;
  currentCondition: number; // percentage (100% = perfect, 0% = failed)
  degradationRate: number; // percentage per week
  affectedComponents: string[];
  recommendedActions: string[];
  estimatedCost: number;
  potentialDowntime: number; // hours
  riskScore: number; // 0-100
  dataPoints: Array<{
    date: string;
    condition: number;
    vibration?: number;
    temperature?: number;
    efficiency?: number;
  }>;
}

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

  // Mock predictive maintenance data - replace with real ML API call
  const maintenanceAlerts: PredictiveMaintenanceAlert[] = [
    {
      id: '1',
      equipmentId: '2',
      equipmentName: 'Mezcladora A',
      equipmentType: 'mixer',
      alertType: 'wear_prediction',
      severity: 'high',
      confidence: 94,
      predictedFailureDate: '2024-02-15',
      currentCondition: 78,
      degradationRate: 3.2,
      affectedComponents: ['Motor principal', 'Correas de transmisión', 'Rodamientos'],
      recommendedActions: [
        'Reemplazar correas de transmisión',
        'Lubricar rodamientos',
        'Inspeccionar motor'
      ],
      estimatedCost: 280,
      potentialDowntime: 4,
      riskScore: 85,
      dataPoints: [
        { date: '2024-01-01', condition: 95, vibration: 1.2, temperature: 35, efficiency: 94 },
        { date: '2024-01-07', condition: 91, vibration: 1.5, temperature: 37, efficiency: 92 },
        { date: '2024-01-14', condition: 87, vibration: 1.8, temperature: 39, efficiency: 89 },
        { date: '2024-01-21', condition: 83, vibration: 2.1, temperature: 41, efficiency: 87 },
        { date: '2024-01-28', condition: 78, vibration: 2.4, temperature: 43, efficiency: 85 }
      ]
    },
    {
      id: '2',
      equipmentId: '1',
      equipmentName: 'Horno Principal',
      equipmentType: 'oven',
      alertType: 'performance_degradation',
      severity: 'medium',
      confidence: 87,
      predictedFailureDate: '2024-03-10',
      currentCondition: 89,
      degradationRate: 1.8,
      affectedComponents: ['Sistema de calefacción', 'Sensores de temperatura'],
      recommendedActions: [
        'Calibrar sensores de temperatura',
        'Limpiar sistema de calefacción',
        'Verificar aislamiento térmico'
      ],
      estimatedCost: 150,
      potentialDowntime: 2,
      riskScore: 65,
      dataPoints: [
        { date: '2024-01-01', condition: 98, temperature: 180, efficiency: 96 },
        { date: '2024-01-07', condition: 95, temperature: 178, efficiency: 95 },
        { date: '2024-01-14', condition: 93, temperature: 176, efficiency: 94 },
        { date: '2024-01-21', condition: 91, temperature: 174, efficiency: 93 },
        { date: '2024-01-28', condition: 89, temperature: 172, efficiency: 92 }
      ]
    },
    {
      id: '3',
      equipmentId: '4',
      equipmentName: 'Empaquetadora',
      equipmentType: 'packaging',
      alertType: 'component_replacement',
      severity: 'low',
      confidence: 76,
      predictedFailureDate: '2024-04-20',
      currentCondition: 92,
      degradationRate: 1.1,
      affectedComponents: ['Cinta transportadora', 'Sistema de sellado'],
      recommendedActions: [
        'Inspeccionar cinta transportadora',
        'Ajustar sistema de sellado',
        'Reemplazar filtros'
      ],
      estimatedCost: 120,
      potentialDowntime: 1.5,
      riskScore: 35,
      dataPoints: [
        { date: '2024-01-01', condition: 98, efficiency: 97 },
        { date: '2024-01-07', condition: 96, efficiency: 96 },
        { date: '2024-01-14', condition: 95, efficiency: 95 },
        { date: '2024-01-21', condition: 94, efficiency: 94 },
        { date: '2024-01-28', condition: 92, efficiency: 93 }
      ]
    }
  ];

  const getSeverityColor = (severity: PredictiveMaintenanceAlert['severity']) => {
    switch (severity) {
      case 'critical': return 'text-red-600';
      case 'high': return 'text-orange-600';
      case 'medium': return 'text-yellow-600';
      case 'low': return 'text-blue-600';
      default: return 'text-gray-600';
    }
  };

  const getSeverityBadgeVariant = (severity: PredictiveMaintenanceAlert['severity']) => {
    switch (severity) {
      case 'critical': return 'error';
      case 'high': return 'warning';
      case 'medium': return 'warning';
      case 'low': return 'info';
      default: return 'default';
    }
  };

  const getAlertTypeIcon = (type: PredictiveMaintenanceAlert['alertType']) => {
    switch (type) {
      case 'wear_prediction': return TrendingDown;
      case 'failure_risk': return AlertTriangle;
      case 'performance_degradation': return Target;
      case 'component_replacement': return Wrench;
      default: return AlertTriangle;
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('es-ES', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
  };

  const getDaysUntilFailure = (failureDate: string) => {
    const today = new Date();
    const failure = new Date(failureDate);
    const diffTime = failure.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  const criticalAlerts = maintenanceAlerts.filter(alert => alert.severity === 'critical');
  const highRiskAlerts = maintenanceAlerts.filter(alert => alert.riskScore > 70);
  const totalEstimatedCost = maintenanceAlerts.reduce((sum, alert) => sum + alert.estimatedCost, 0);
  const totalPotentialDowntime = maintenanceAlerts.reduce((sum, alert) => sum + alert.potentialDowntime, 0);
  const avgConfidence = maintenanceAlerts.reduce((sum, alert) => sum + alert.confidence, 0) / maintenanceAlerts.length;

  // Create equipment condition trend chart
  const getConditionTrendChartData = (): ChartSeries[] => {
    return maintenanceAlerts.map((alert, index) => ({
      id: `condition-${alert.equipmentId}`,
      name: alert.equipmentName,
      type: 'line',
      color: ['#ef4444', '#f97316', '#eab308'][index % 3],
      data: alert.dataPoints.map(point => ({
        x: new Date(point.date).toLocaleDateString('es-ES', { month: 'short', day: 'numeric' }),
        y: point.condition,
        label: `${point.condition}%`
      }))
    }));
  };

  // Create risk score distribution chart
  const getRiskDistributionChartData = (): ChartSeries[] => {
    const lowRisk = maintenanceAlerts.filter(a => a.riskScore <= 40).length;
    const mediumRisk = maintenanceAlerts.filter(a => a.riskScore > 40 && a.riskScore <= 70).length;
    const highRisk = maintenanceAlerts.filter(a => a.riskScore > 70).length;

    return [
      {
        id: 'risk-distribution',
        name: 'Risk Distribution',
        type: 'doughnut',
        color: '#3b82f6',
        data: [
          { x: t('ai.risk.low'), y: lowRisk, label: `${t('ai.risk.low')}: ${lowRisk}` },
          { x: t('ai.risk.medium'), y: mediumRisk, label: `${t('ai.risk.medium')}: ${mediumRisk}` },
          { x: t('ai.risk.high'), y: highRisk, label: `${t('ai.risk.high')}: ${highRisk}` }
        ].filter(item => item.y > 0)
      }
    ];
  };

  return (
    <AnalyticsWidget
      title={t('ai.predictive_maintenance.title')}
      subtitle={t('ai.predictive_maintenance.subtitle')}
      icon={Brain}
      actions={
        <div className="flex space-x-2">
          <Button variant="outline" size="sm">
            <Calendar className="w-4 h-4 mr-1" />
            {t('ai.predictive_maintenance.schedule_all')}
          </Button>
          <Button variant="primary" size="sm">
            <Brain className="w-4 h-4 mr-1" />
            {t('ai.predictive_maintenance.retrain_model')}
          </Button>
        </div>
      }
    >
      <div className="space-y-6">
        {/* Predictive Maintenance 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">
            <AlertTriangle className="w-8 h-8 mx-auto text-red-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{highRiskAlerts.length}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('ai.predictive_maintenance.high_risk')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <div className="w-8 h-8 mx-auto bg-orange-100 dark:bg-orange-900/20 rounded-full flex items-center justify-center mb-2">
              <span className="text-orange-600 font-bold text-sm">{currencySymbol}</span>
            </div>
            <p className="text-2xl font-bold text-[var(--text-primary)]">{currencySymbol}{totalEstimatedCost}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('ai.predictive_maintenance.estimated_cost')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <div className="w-8 h-8 mx-auto bg-red-100 dark:bg-red-900/20 rounded-full flex items-center justify-center mb-2">
              <span className="text-red-600 font-bold text-xs">h</span>
            </div>
            <p className="text-2xl font-bold text-[var(--text-primary)]">{totalPotentialDowntime}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('ai.predictive_maintenance.potential_downtime')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <div className="w-8 h-8 mx-auto bg-blue-100 dark:bg-blue-900/20 rounded-full flex items-center justify-center mb-2">
              <span className="text-blue-600 font-bold text-sm">%</span>
            </div>
            <p className="text-2xl font-bold text-[var(--text-primary)]">{avgConfidence.toFixed(0)}%</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('ai.predictive_maintenance.avg_confidence')}</p>
          </div>
        </div>

        {/* Critical Alerts */}
        {highRiskAlerts.length > 0 && (
          <div className="p-4 bg-red-50 dark:bg-red-900/20 rounded-lg">
            <div className="flex items-start space-x-2">
              <AlertTriangle className="w-5 h-5 text-red-600 mt-0.5" />
              <div>
                <p className="text-sm font-medium text-red-600">
                  {t('ai.predictive_maintenance.high_risk_equipment')} ({highRiskAlerts.length})
                </p>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('ai.predictive_maintenance.immediate_attention_required')}
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Maintenance Predictions */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3 flex items-center">
            <Brain className="w-4 h-4 mr-2" />
            {t('ai.predictive_maintenance.predictions')} ({maintenanceAlerts.length})
          </h4>
          <div className="space-y-4">
            {maintenanceAlerts.map((alert) => {
              const AlertTypeIcon = getAlertTypeIcon(alert.alertType);
              const daysUntilFailure = getDaysUntilFailure(alert.predictedFailureDate);

              return (
                <div key={alert.id} className="p-4 bg-[var(--bg-secondary)] rounded-lg">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start space-x-3">
                      <AlertTypeIcon className={`w-5 h-5 mt-1 ${getSeverityColor(alert.severity)}`} />
                      <div className="flex-1">
                        <div className="flex items-center space-x-2 mb-1">
                          <p className="font-medium text-[var(--text-primary)]">{alert.equipmentName}</p>
                          <Badge variant={getSeverityBadgeVariant(alert.severity)}>
                            {t(`ai.severity.${alert.severity}`)}
                          </Badge>
                        </div>
                        <div className="flex items-center space-x-4 text-xs text-[var(--text-secondary)] mb-2">
                          <span>{t('ai.predictive_maintenance.confidence')}: {alert.confidence}%</span>
                          <span>{t('ai.predictive_maintenance.risk_score')}: {alert.riskScore}/100</span>
                          <span>{t('ai.predictive_maintenance.days_until_failure')}: {daysUntilFailure}</span>
                        </div>
                        <p className="text-sm text-[var(--text-secondary)] mb-2">
                          {t(`ai.predictive_maintenance.alert_type.${alert.alertType}`)}
                        </p>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-lg font-bold text-[var(--text-primary)]">{alert.currentCondition}%</div>
                      <div className="text-xs text-[var(--text-secondary)]">{t('ai.predictive_maintenance.condition')}</div>
                    </div>
                  </div>

                  {/* Condition Progress Bar */}
                  <div className="mb-3">
                    <div className="flex justify-between text-xs text-[var(--text-secondary)] mb-1">
                      <span>{t('ai.predictive_maintenance.current_condition')}</span>
                      <span>{alert.currentCondition}%</span>
                    </div>
                    <div className="w-full bg-[var(--bg-tertiary)] rounded-full h-2">
                      <div
                        className={`h-2 rounded-full transition-all duration-300 ${
                          alert.currentCondition > 80 ? 'bg-green-500' :
                          alert.currentCondition > 60 ? 'bg-yellow-500' :
                          alert.currentCondition > 40 ? 'bg-orange-500' : 'bg-red-500'
                        }`}
                        style={{ width: `${alert.currentCondition}%` }}
                      />
                    </div>
                  </div>

                  {/* Affected Components */}
                  <div className="mb-3">
                    <p className="text-xs font-medium text-[var(--text-primary)] mb-1">
                      {t('ai.predictive_maintenance.affected_components')}:
                    </p>
                    <div className="flex flex-wrap gap-1">
                      {alert.affectedComponents.map((component, index) => (
                        <Badge key={index} variant="outline" className="text-xs">
                          {component}
                        </Badge>
                      ))}
                    </div>
                  </div>

                  {/* Recommended Actions */}
                  <div className="mb-3">
                    <p className="text-xs font-medium text-[var(--text-primary)] mb-1">
                      {t('ai.predictive_maintenance.recommended_actions')}:
                    </p>
                    <ul className="text-xs text-[var(--text-secondary)] space-y-1">
                      {alert.recommendedActions.map((action, index) => (
                        <li key={index}>• {action}</li>
                      ))}
                    </ul>
                  </div>

                  {/* Cost and Downtime */}
                  <div className="flex items-center justify-between p-3 bg-[var(--bg-tertiary)] rounded-lg">
                    <div className="flex items-center space-x-4 text-xs">
                      <span className="flex items-center space-x-1">
                        <span className="w-2 h-2 bg-orange-500 rounded-full"></span>
                        <span>{t('ai.predictive_maintenance.estimated_cost')}: {currencySymbol}{alert.estimatedCost}</span>
                      </span>
                      <span className="flex items-center space-x-1">
                        <span className="w-2 h-2 bg-red-500 rounded-full"></span>
                        <span>{t('ai.predictive_maintenance.potential_downtime')}: {alert.potentialDowntime}h</span>
                      </span>
                    </div>
                    <div className="flex space-x-2">
                      <Button variant="outline" size="sm">
                        {t('ai.predictive_maintenance.schedule')}
                      </Button>
                      <Button variant="primary" size="sm">
                        {t('ai.predictive_maintenance.details')}
                      </Button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Charts */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Equipment Condition Trends */}
          <div>
            <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
              {t('ai.predictive_maintenance.condition_trends')}
            </h4>
            <AnalyticsChart
              series={getConditionTrendChartData()}
              height={200}
              showLegend={true}
              showGrid={true}
            />
          </div>

          {/* Risk Distribution */}
          <div>
            <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
              {t('ai.predictive_maintenance.risk_distribution')}
            </h4>
            <AnalyticsChart
              series={getRiskDistributionChartData()}
              height={200}
              showLegend={true}
              showGrid={false}
            />
          </div>
        </div>

        {/* ML Model Status */}
        <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
          <div className="flex items-start space-x-2">
            <Brain className="w-5 h-5 text-blue-600 mt-0.5" />
            <div>
              <p className="text-sm font-medium text-blue-600">
                {t('ai.predictive_maintenance.model_status')}
              </p>
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('ai.predictive_maintenance.last_training')}: {t('ai.predictive_maintenance.yesterday')}.
                {t('ai.predictive_maintenance.accuracy')}: 94%. {t('ai.predictive_maintenance.next_training')}: {t('ai.predictive_maintenance.in_7_days')}.
              </p>
            </div>
          </div>
        </div>
      </div>
    </AnalyticsWidget>
  );
};