/**
 * ProductionStatusBlock - Block 4: "Estado de Produccion"
 *
 * Displays today's production overview:
 * - Late to start batches (should have started but haven't)
 * - Currently running batches (IN_PROGRESS)
 * - Pending batches for today
 * - AI reasoning for batch scheduling
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  AlertTriangle,
  Brain,
  CheckCircle2,
  ChevronDown,
  ChevronUp,
  Clock,
  Factory,
  Play,
  Timer,
} from 'lucide-react';

interface ProductionStatusBlockProps {
  lateToStartBatches?: any[];
  runningBatches?: any[];
  pendingBatches?: any[];
  alerts?: any[]; // Add alerts prop for production-related alerts
  equipmentAlerts?: any[]; // Equipment-specific alerts
  productionAlerts?: any[]; // Production alerts (non-equipment)
  onStartBatch?: (batchId: string) => Promise<void>;
  onViewBatch?: (batchId: string) => void;
  loading?: boolean;
}

export function ProductionStatusBlock({
  lateToStartBatches = [],
  runningBatches = [],
  pendingBatches = [],
  alerts = [],
  equipmentAlerts = [],
  productionAlerts = [],
  onStartBatch,
  onViewBatch,
  loading,
}: ProductionStatusBlockProps) {
  const { t } = useTranslation(['dashboard', 'common', 'production']);
  const [expandedReasoningId, setExpandedReasoningId] = useState<string | null>(null);
  const [processingId, setProcessingId] = useState<string | null>(null);

  // Filter production-related alerts and deduplicate by ID
  // Also filter out alerts for batches already shown in late/running/pending sections
  const filteredProductionAlerts = React.useMemo(() => {
    const filtered = alerts.filter((alert: any) => {
      const eventType = alert.event_type || '';
      
      // First filter by event type
      const isProductionAlert = eventType.includes('production.') ||
                               eventType.includes('equipment_maintenance') ||
                               eventType.includes('production_delay') ||
                               eventType.includes('batch_start_delayed');
      
      if (!isProductionAlert) return false;
      
      // Get batch ID from alert
      const batchId = alert.event_metadata?.batch_id || alert.entity_links?.production_batch;
      
      // Filter out alerts for batches already shown in UI sections
      if (batchId) {
        const isLateBatch = lateToStartBatches.some(batch => batch.id === batchId);
        const isRunningBatch = runningBatches.some(batch => batch.id === batchId);
        const isPendingBatch = pendingBatches.some(batch => batch.id === batchId);
        
        // If this alert is about a batch already shown, filter it out to prevent duplication
        if (isLateBatch || isRunningBatch || isPendingBatch) {
          return false;
        }
      }
      
      return true;
    });

    // Deduplicate by alert ID to prevent duplicates from API + SSE
    const uniqueAlerts = new Map<string, any>();
    filtered.forEach((alert: any) => {
      const alertId = alert.id || alert.event_id;
      if (alertId && !uniqueAlerts.has(alertId)) {
        uniqueAlerts.set(alertId, alert);
      }
    });

    return Array.from(uniqueAlerts.values());
  }, [alerts, lateToStartBatches, runningBatches, pendingBatches]);

  if (loading) {
    return (
      <div className="rounded-xl shadow-lg p-6 border border-[var(--border-primary)] bg-[var(--bg-primary)] animate-pulse">
        <div className="flex items-center gap-4 mb-4">
          <div className="w-12 h-12 bg-[var(--bg-secondary)] rounded-full"></div>
          <div className="flex-1 space-y-2">
            <div className="h-5 bg-[var(--bg-secondary)] rounded w-1/3"></div>
            <div className="h-4 bg-[var(--bg-secondary)] rounded w-1/4"></div>
          </div>
        </div>
        <div className="space-y-3">
          <div className="h-20 bg-[var(--bg-secondary)] rounded"></div>
          <div className="h-20 bg-[var(--bg-secondary)] rounded"></div>
        </div>
      </div>
    );
  }

  const hasLate = lateToStartBatches.length > 0;
  const hasRunning = runningBatches.length > 0;
  const hasPending = pendingBatches.length > 0;
  const hasEquipmentAlerts = equipmentAlerts.length > 0;
  const hasProductionAlerts = filteredProductionAlerts.length > 0;
  const hasAlerts = hasEquipmentAlerts || hasProductionAlerts;
  const hasAnyProduction = hasLate || hasRunning || hasPending || hasAlerts;
  const totalCount = lateToStartBatches.length + runningBatches.length + pendingBatches.length;

  // Determine header status - prioritize equipment alerts, then production alerts, then late batches
  const status = hasEquipmentAlerts ? 'error' : hasProductionAlerts || hasLate ? 'warning' : hasRunning ? 'info' : hasPending ? 'warning' : 'success';

  const statusStyles = {
    success: {
      iconBg: 'bg-[var(--color-success-100)]',
      iconColor: 'text-[var(--color-success-600)]',
    },
    warning: {
      iconBg: 'bg-[var(--color-warning-100)]',
      iconColor: 'text-[var(--color-warning-600)]',
    },
    info: {
      iconBg: 'bg-[var(--color-info-100)]',
      iconColor: 'text-[var(--color-info-600)]',
    },
    error: {
      iconBg: 'bg-[var(--color-error-100)]',
      iconColor: 'text-[var(--color-error-600)]',
    },
  };

  const styles = statusStyles[status];

  // Handle start batch
  const handleStartBatch = async (batchId: string) => {
    if (!onStartBatch || processingId) return;
    setProcessingId(batchId);
    try {
      await onStartBatch(batchId);
    } finally {
      setProcessingId(null);
    }
  };

  // Toggle reasoning expansion
  const toggleReasoning = (batchId: string) => {
    setExpandedReasoningId(expandedReasoningId === batchId ? null : batchId);
  };

  // Format AI reasoning
  const formatReasoning = (batch: any): string | null => {
    const reasoningData = batch.reasoning_data;
    if (!reasoningData) return null;

    if (typeof reasoningData === 'string') return reasoningData;

    if (reasoningData.type === 'forecast_demand') {
      // Check if this is enhanced reasoning with factors
      if (reasoningData.parameters?.factors && reasoningData.parameters.factors.length > 0) {
        return t('dashboard:new_dashboard.production_status.reasoning.forecast_demand_enhanced', {
          product: reasoningData.parameters?.product_name || batch.product_name,
          demand: reasoningData.parameters?.predicted_demand || batch.planned_quantity,
          variance: reasoningData.parameters?.variance_percent || 0,
        });
      } else {
        return t('dashboard:new_dashboard.production_status.reasoning.forecast_demand', {
          product: reasoningData.parameters?.product_name || batch.product_name,
          demand: reasoningData.parameters?.predicted_demand || batch.planned_quantity,
        });
      }
    }

    if (reasoningData.type === 'customer_order') {
      return t('dashboard:new_dashboard.production_status.reasoning.customer_order', {
        customer: reasoningData.parameters?.customer_name || 'customer',
      });
    }


    if (reasoningData.summary) return reasoningData.summary;

    return null;
  };

  // Get factor icon based on type (handles both uppercase and lowercase formats)
  const getFactorIcon = (factorType: string) => {
    const normalizedFactor = factorType?.toLowerCase() || '';
    if (normalizedFactor.includes('historical') || normalizedFactor === 'historical_pattern') return '📊';
    if (normalizedFactor.includes('sunny') || normalizedFactor === 'weather_sunny') return '☀️';
    if (normalizedFactor.includes('rainy') || normalizedFactor === 'weather_rainy') return '🌧️';
    if (normalizedFactor.includes('cold') || normalizedFactor === 'weather_cold') return '❄️';
    if (normalizedFactor.includes('hot') || normalizedFactor === 'weather_hot') return '🔥';
    if (normalizedFactor.includes('weekend') || normalizedFactor === 'weekend_boost') return '📅';
    if (normalizedFactor.includes('inventory') || normalizedFactor === 'inventory_level') return '📦';
    if (normalizedFactor.includes('seasonal') || normalizedFactor === 'seasonal_trend') return '🍂';
    return 'ℹ️';
  };

  // Get factor translation key (handles both uppercase and lowercase formats)
  const getFactorTranslationKey = (factorType: string) => {
    const normalizedFactor = factorType?.toLowerCase().replace(/\s+/g, '_') || '';

    // Direct mapping for exact matches
    const factorMap: Record<string, string> = {
      'historical_pattern': 'historical_pattern',
      'historical_sales_pattern': 'historical_pattern',
      'weather_sunny': 'weather_sunny',
      'weather_impact_sunny': 'weather_sunny',
      'weather_rainy': 'weather_rainy',
      'weather_cold': 'weather_cold',
      'weather_hot': 'weather_hot',
      'weekend_boost': 'weekend_boost',
      'inventory_level': 'inventory_level',
      'current_inventory_trigger': 'inventory_level',
      'seasonal_trend': 'seasonal_trend',
      'seasonal_trend_adjustment': 'seasonal_trend',
    };

    // Check for direct match
    if (factorMap[normalizedFactor]) {
      return `dashboard:new_dashboard.production_status.factors.${factorMap[normalizedFactor]}`;
    }

    // Fallback to partial matching
    if (normalizedFactor.includes('historical')) {
      return 'dashboard:new_dashboard.production_status.factors.historical_pattern';
    }
    if (normalizedFactor.includes('sunny')) {
      return 'dashboard:new_dashboard.production_status.factors.weather_sunny';
    }
    if (normalizedFactor.includes('rainy')) {
      return 'dashboard:new_dashboard.production_status.factors.weather_rainy';
    }
    if (normalizedFactor.includes('cold')) {
      return 'dashboard:new_dashboard.production_status.factors.weather_cold';
    }
    if (normalizedFactor.includes('hot')) {
      return 'dashboard:new_dashboard.production_status.factors.weather_hot';
    }
    if (normalizedFactor.includes('weekend')) {
      return 'dashboard:new_dashboard.production_status.factors.weekend_boost';
    }
    if (normalizedFactor.includes('inventory')) {
      return 'dashboard:new_dashboard.production_status.factors.inventory_level';
    }
    if (normalizedFactor.includes('seasonal')) {
      return 'dashboard:new_dashboard.production_status.factors.seasonal_trend';
    }
    return 'dashboard:new_dashboard.production_status.factors.general';
  };

  // Format time
  const formatTime = (isoString: string | null | undefined) => {
    if (!isoString) return '--:--';
    const date = new Date(isoString);
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  // Calculate progress percentage for running batches
  const calculateProgress = (batch: any): number => {
    if (!batch.actual_start_time || !batch.planned_end_time) return 0;

    const start = new Date(batch.actual_start_time).getTime();
    const end = new Date(batch.planned_end_time).getTime();
    const now = Date.now();

    if (now >= end) return 100;
    if (now <= start) return 0;

    return Math.round(((now - start) / (end - start)) * 100);
  };

  // Render an alert item
  const renderAlertItem = (alert: any, index: number, total: number) => {
    const alertId = alert.id || alert.event_id;
    const eventType = alert.event_type || '';
    const priorityLevel = alert.priority_level || 'standard';
    const businessImpact = alert.business_impact || {};
    const urgency = alert.urgency || {};
    const metadata = alert.event_metadata || {};

    // Determine alert icon and type
    let icon = <AlertTriangle className="w-4 h-4 text-[var(--color-error-600)]" />;
    let alertTitle = '';
    let alertDescription = '';

    if (eventType.includes('equipment_maintenance')) {
      icon = <AlertTriangle className="w-4 h-4 text-[var(--color-warning-600)]" />;
      alertTitle = alert.title || t('dashboard:new_dashboard.production_status.alerts.equipment_maintenance');
      alertDescription = alert.description || alert.message || '';
    } else if (eventType.includes('production_delay')) {
      icon = <Clock className="w-4 h-4 text-[var(--color-error-600)]" />;
      alertTitle = alert.title || t('dashboard:new_dashboard.production_status.alerts.production_delay');
      alertDescription = alert.description || alert.message || '';
    } else if (eventType.includes('batch_start_delayed')) {
      icon = <AlertTriangle className="w-4 h-4 text-[var(--color-warning-600)]" />;
      alertTitle = alert.title || t('dashboard:new_dashboard.production_status.alerts.batch_delayed');
      alertDescription = alert.description || alert.message || '';
    } else {
      alertTitle = alert.title || t('dashboard:new_dashboard.production_status.alerts.generic');
      alertDescription = alert.description || alert.message || '';
    }

    // Priority badge styling
    const priorityStyles = {
      critical: 'bg-[var(--color-error-100)] text-[var(--color-error-700)]',
      important: 'bg-[var(--color-warning-100)] text-[var(--color-warning-700)]',
      standard: 'bg-[var(--color-info-100)] text-[var(--color-info-700)]',
      info: 'bg-[var(--bg-tertiary)] text-[var(--text-tertiary)]',
    };

    // Format time ago
    const formatTimeAgo = (isoString: string) => {
      const date = new Date(isoString);
      const now = new Date();
      const diffMs = now.getTime() - date.getTime();
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMins / 60);

      if (diffMins < 1) return t('common:time.just_now');
      if (diffMins < 60) return t('common:time.minutes_ago', { count: diffMins });
      if (diffHours < 24) return t('common:time.hours_ago', { count: diffHours });
      return t('common:time.days_ago', { count: Math.floor(diffHours / 24) });
    };

    return (
      <div
        key={alertId || index}
        className={`p-4 ${index < total - 1 ? 'border-b border-[var(--border-primary)]' : ''}`}
      >
        <div className="flex items-start gap-4">
          <div className="flex-1 min-w-0">
            {/* Header */}
            <div className="flex items-center gap-2 mb-2 flex-wrap">
              {icon}
              <span className="font-semibold text-[var(--text-primary)]">
                {alertTitle}
              </span>
              <div className={`px-2 py-0.5 rounded-full text-xs font-medium ${priorityStyles[priorityLevel as keyof typeof priorityStyles] || priorityStyles.standard}`}>
                {t(`dashboard:new_dashboard.production_status.priority.${priorityLevel}`)}
              </div>
              {alert.created_at && (
                <span className="text-xs text-[var(--text-tertiary)]">
                  {formatTimeAgo(alert.created_at)}
                </span>
              )}
            </div>

            {/* Description */}
            <p className="text-sm text-[var(--text-secondary)] mb-2">
              {alertDescription}
            </p>

            {/* Additional Details */}
            <div className="flex flex-wrap gap-3 text-xs">
              {/* Business Impact */}
              {businessImpact.affected_orders > 0 && (
                <div className="flex items-center gap-1 text-[var(--text-tertiary)]">
                  <span>📦</span>
                  <span>
                    {t('dashboard:new_dashboard.production_status.alerts.affected_orders', {
                      count: businessImpact.affected_orders
                    })}
                  </span>
                </div>
              )}

              {businessImpact.production_delay_hours > 0 && (
                <div className="flex items-center gap-1 text-[var(--text-tertiary)]">
                  <Clock className="w-3 h-3" />
                  <span>
                    {t('dashboard:new_dashboard.production_status.alerts.delay_hours', {
                      hours: Math.round(businessImpact.production_delay_hours * 10) / 10
                    })}
                  </span>
                </div>
              )}

              {businessImpact.financial_impact_eur > 0 && (
                <div className="flex items-center gap-1 text-[var(--text-tertiary)]">
                  <span>💰</span>
                  <span>
                    {t('dashboard:new_dashboard.production_status.alerts.financial_impact', {
                      amount: Math.round(businessImpact.financial_impact_eur)
                    })}
                  </span>
                </div>
              )}

              {/* Urgency Info */}
              {urgency.hours_until_consequence !== undefined && urgency.hours_until_consequence < 24 && (
                <div className="flex items-center gap-1 text-[var(--color-warning-600)] font-medium">
                  <Timer className="w-3 h-3" />
                  <span>
                    {t('dashboard:new_dashboard.production_status.alerts.urgent_in', {
                      hours: Math.round(urgency.hours_until_consequence * 10) / 10
                    })}
                  </span>
                </div>
              )}

              {/* Product/Batch Info from metadata */}
              {metadata.product_name && (
                <div className="flex items-center gap-1 text-[var(--text-tertiary)]">
                  <span>🥖</span>
                  <span>{metadata.product_name}</span>
                </div>
              )}

              {metadata.batch_number && (
                <div className="flex items-center gap-1 text-[var(--text-tertiary)]">
                  <span>#</span>
                  <span>{metadata.batch_number}</span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Render a batch item
  const renderBatchItem = (batch: any, type: 'late' | 'running' | 'pending', index: number, total: number) => {
    const batchId = batch.id || batch.batch_id;
    const isProcessing = processingId === batchId;
    const isExpanded = expandedReasoningId === batchId;
    const reasoning = formatReasoning(batch);
    const progress = type === 'running' ? calculateProgress(batch) : 0;

    const typeStyles = {
      late: {
        timeBg: 'bg-[var(--color-error-100)]',
        timeColor: 'text-[var(--color-error-700)]',
        icon: <AlertTriangle className="w-4 h-4 text-[var(--color-error-600)]" />,
      },
      running: {
        timeBg: 'bg-[var(--color-info-100)]',
        timeColor: 'text-[var(--color-info-700)]',
        icon: <Timer className="w-4 h-4 text-[var(--color-info-600)]" />,
      },
      pending: {
        timeBg: 'bg-[var(--color-warning-100)]',
        timeColor: 'text-[var(--color-warning-700)]',
        icon: <Clock className="w-4 h-4 text-[var(--text-tertiary)]" />,
      },
    };

    const batchStyles = typeStyles[type];

    return (
      <div
        key={batchId || index}
        className={`p-4 ${index < total - 1 ? 'border-b border-[var(--border-primary)]' : ''}`}
      >
        <div className="flex items-start gap-4">
          {/* Batch Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              {batchStyles.icon}
              <span className="font-semibold text-[var(--text-primary)]">
                {batch.product_name || 'Unknown Product'}
              </span>
              {reasoning && (
                <button
                  onClick={() => toggleReasoning(batchId)}
                  className="flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-[var(--color-primary-50)] text-[var(--color-primary-700)] hover:bg-[var(--color-primary-100)] transition-colors"
                >
                  <Brain className="w-3 h-3" />
                  AI
                  {isExpanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
                </button>
              )}
            </div>

            <p className="text-sm text-[var(--text-secondary)] mb-2">
              {t('dashboard:new_dashboard.production_status.batch_info', {
                number: batch.batch_number || batchId?.slice(0, 8),
                quantity: batch.planned_quantity || 0,
              })}
            </p>

            {/* Time/Status Badge */}
            <div className="flex items-center gap-2">
              {type === 'late' && (
                <div className={`inline-flex items-center gap-1 px-2 py-1 rounded ${batchStyles.timeBg} ${batchStyles.timeColor} text-xs font-medium`}>
                  <Clock className="w-3 h-3" />
                  {t('dashboard:new_dashboard.production_status.should_have_started', {
                    time: formatTime(batch.planned_start_time),
                  })}
                </div>
              )}

              {type === 'running' && (
                <>
                  <div className={`inline-flex items-center gap-1 px-2 py-1 rounded ${batchStyles.timeBg} ${batchStyles.timeColor} text-xs font-medium`}>
                    <Timer className="w-3 h-3" />
                    {t('dashboard:new_dashboard.production_status.started_at', {
                      time: formatTime(batch.actual_start_time),
                    })}
                  </div>
                  {/* Progress Bar */}
                  <div className="flex-1 max-w-[120px]">
                    <div className="h-2 bg-[var(--bg-tertiary)] rounded-full overflow-hidden">
                      <div
                        className="h-full bg-[var(--color-info-500)] transition-all"
                        style={{ width: `${progress}%` }}
                      />
                    </div>
                    <span className="text-xs text-[var(--text-tertiary)]">{progress}%</span>
                  </div>
                </>
              )}

              {type === 'pending' && batch.planned_start_time && (
                <div className={`inline-flex items-center gap-1 px-2 py-1 rounded ${batchStyles.timeBg} ${batchStyles.timeColor} text-xs font-medium`}>
                  <Clock className="w-3 h-3" />
                  {t('dashboard:new_dashboard.production_status.starts_at', {
                    time: formatTime(batch.planned_start_time),
                  })}
                </div>
              )}
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center gap-2 flex-shrink-0">
            {(type === 'late' || type === 'pending') && onStartBatch && (
              <button
                onClick={() => handleStartBatch(batchId)}
                disabled={isProcessing}
                className="flex items-center gap-2 px-3 py-2 rounded-lg bg-[var(--color-success-600)] text-white hover:bg-[var(--color-success-700)] transition-colors disabled:opacity-50"
              >
                <Play className="w-4 h-4" />
                <span className="text-sm font-medium">
                  {t('dashboard:new_dashboard.production_status.start_batch')}
                </span>
              </button>
            )}

            {type === 'running' && onViewBatch && (
              <button
                onClick={() => onViewBatch(batchId)}
                className="flex items-center gap-2 px-3 py-2 rounded-lg border border-[var(--border-primary)] text-[var(--text-primary)] hover:bg-[var(--bg-secondary)] transition-colors"
              >
                <span className="text-sm font-medium">
                  {t('dashboard:new_dashboard.production_status.view_details')}
                </span>
              </button>
            )}
          </div>
        </div>

        {/* AI Reasoning (Expanded) */}
        {isExpanded && reasoning && (
          <div className="mt-3 p-3 rounded-lg bg-[var(--color-primary-50)] border border-[var(--color-primary-100)]">
            <div className="flex items-start gap-2">
              <Brain className="w-4 h-4 text-[var(--color-primary-600)] mt-0.5 flex-shrink-0" />
              <div className="w-full">
                <p className="text-sm font-medium text-[var(--color-primary-700)] mb-1">
                  {t('dashboard:new_dashboard.production_status.ai_reasoning')}
                </p>
                <p className="text-sm text-[var(--color-primary-600)] mb-2">{reasoning}</p>

                {/* Weather Data Display */}
                {batch.reasoning_data?.parameters?.weather_data && (
                  <div className="mb-3 p-2 rounded-lg bg-[var(--bg-primary)] border border-[var(--color-primary-200)]">
                    <div className="flex items-center gap-3">
                      <span className="text-2xl">
                        {batch.reasoning_data.parameters.weather_data.condition === 'sunny' && '☀️'}
                        {batch.reasoning_data.parameters.weather_data.condition === 'rainy' && '🌧️'}
                        {batch.reasoning_data.parameters.weather_data.condition === 'cold' && '❄️'}
                        {batch.reasoning_data.parameters.weather_data.condition === 'hot' && '🔥'}
                      </span>
                      <div className="flex-1">
                        <p className="text-xs font-semibold text-[var(--text-primary)] uppercase">
                          {t('dashboard:new_dashboard.production_status.weather_forecast')}
                        </p>
                        <p className="text-sm text-[var(--text-secondary)]">
                          {t(`dashboard:new_dashboard.production_status.weather_conditions.${batch.reasoning_data.parameters.weather_data.condition}`, {
                            temp: batch.reasoning_data.parameters.weather_data.temperature,
                            humidity: batch.reasoning_data.parameters.weather_data.humidity
                          })}
                        </p>
                      </div>
                      <div className="text-right">
                        <p className="text-xs text-[var(--text-tertiary)]">
                          {t('dashboard:new_dashboard.production_status.demand_impact')}
                        </p>
                        <p className={`text-sm font-semibold ${
                          batch.reasoning_data.parameters.weather_data.impact_factor > 1
                            ? 'text-[var(--color-success-600)]'
                            : 'text-[var(--color-warning-600)]'
                        }`}>
                          {batch.reasoning_data.parameters.weather_data.impact_factor > 1 ? '+' : ''}
                          {Math.round((batch.reasoning_data.parameters.weather_data.impact_factor - 1) * 100)}%
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                {/* Enhanced reasoning with factors */}
                {batch.reasoning_data?.parameters?.factors && batch.reasoning_data.parameters.factors.length > 0 && (
                  <div className="mt-2 space-y-2">
                    <p className="text-xs font-medium text-[var(--color-primary-800)] uppercase tracking-wide">
                      {t('dashboard:new_dashboard.production_status.factors_title')}
                    </p>

                    <div className="space-y-2">
                      {batch.reasoning_data.parameters.factors.map((factor: any, factorIndex: number) => (
                        <div key={factorIndex} className="flex items-center gap-2">
                          <span className="text-lg">{getFactorIcon(factor.factor)}</span>
                          <div className="flex-1">
                            <div className="flex items-center gap-2">
                              <span className="text-xs font-medium text-[var(--text-secondary)]">
                                {t(getFactorTranslationKey(factor.factor))}
                              </span>
                              <span className="text-xs text-[var(--text-tertiary)]">
                                ({Math.round(factor.weight * 100)}%)
                              </span>
                            </div>
                            <div className="w-full bg-[var(--bg-tertiary)] rounded-full h-1.5 mt-1">
                              <div
                                className="bg-[var(--color-primary-500)] h-1.5 rounded-full transition-all"
                                style={{ width: `${Math.round(factor.weight * 100)}%` }}
                              />
                            </div>
                          </div>
                          <span className={`text-sm font-semibold ${
                            factor.contribution >= 0
                              ? 'text-[var(--color-success-600)]'
                              : 'text-[var(--color-error-600)]'
                          }`}>
                            {factor.contribution >= 0 ? '+' : ''}{Math.round(factor.contribution)}
                          </span>
                        </div>
                      ))}
                    </div>

                    {/* Confidence and variance info */}
                    <div className="mt-2 pt-2 border-t border-[var(--color-primary-100)] flex flex-wrap items-center gap-4 text-xs">
                      {batch.reasoning_data.metadata?.confidence_score && (
                        <div className="flex items-center gap-1 text-[var(--text-secondary)]">
                          <span className="text-[var(--color-primary-600)]">🎯</span>
                          <span>
                            {t('dashboard:new_dashboard.production_status.confidence', {
                              confidence: Math.round(batch.reasoning_data.metadata.confidence_score * 100)
                            })}
                          </span>
                        </div>
                      )}
                      {batch.reasoning_data.parameters?.variance_percent && (
                        <div className="flex items-center gap-1 text-[var(--text-secondary)]">
                          <span className="text-[var(--color-primary-600)]">📈</span>
                          <span>
                            {t('dashboard:new_dashboard.production_status.variance', {
                              variance: batch.reasoning_data.parameters.variance_percent
                            })}
                          </span>
                        </div>
                      )}
                      {batch.reasoning_data.parameters?.historical_average && (
                        <div className="flex items-center gap-1 text-[var(--text-secondary)]">
                          <span className="text-[var(--color-primary-600)]">📊</span>
                          <span>
                            {t('dashboard:new_dashboard.production_status.historical_avg', {
                              avg: Math.round(batch.reasoning_data.parameters.historical_average)
                            })}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="rounded-xl shadow-lg border border-[var(--border-primary)] bg-[var(--bg-primary)] overflow-hidden">
      {/* Header */}
      <div className="p-6 pb-4">
        <div className="flex items-center gap-4">
          {/* Icon */}
          <div className={`w-12 h-12 rounded-full flex items-center justify-center flex-shrink-0 ${styles.iconBg}`}>
            {hasLate ? (
              <AlertTriangle className={`w-6 h-6 ${styles.iconColor}`} />
            ) : hasAnyProduction ? (
              <Factory className={`w-6 h-6 ${styles.iconColor}`} />
            ) : (
              <CheckCircle2 className={`w-6 h-6 ${styles.iconColor}`} />
            )}
          </div>

          {/* Title & Count */}
          <div className="flex-1">
            <h2 className="text-xl font-bold text-[var(--text-primary)]">
              {t('dashboard:new_dashboard.production_status.title')}
            </h2>
            <p className="text-sm text-[var(--text-secondary)]">
              {hasAnyProduction
                ? t('dashboard:new_dashboard.production_status.count', { count: totalCount })
                : t('dashboard:new_dashboard.production_status.no_production')}
            </p>
          </div>

          {/* Count Badges */}
          <div className="flex items-center gap-2">
            {hasLate && (
              <div className="px-3 py-1 rounded-full bg-[var(--color-error-100)] text-[var(--color-error-700)] font-semibold text-sm">
                {lateToStartBatches.length} {t('dashboard:new_dashboard.production_status.late_badge')}
              </div>
            )}
            {hasRunning && (
              <div className="px-3 py-1 rounded-full bg-[var(--color-info-100)] text-[var(--color-info-700)] font-semibold text-sm">
                {runningBatches.length} {t('dashboard:new_dashboard.production_status.running_badge')}
              </div>
            )}
            {hasPending && (
              <div className="px-3 py-1 rounded-full bg-[var(--color-warning-100)] text-[var(--color-warning-700)] font-semibold text-sm">
                {pendingBatches.length}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Content */}
      {hasAnyProduction ? (
        <div className="border-t border-[var(--border-primary)]">
          {/* Equipment Alerts Section */}
          {equipmentAlerts.length > 0 && (
            <div className="bg-[var(--color-error-50)]">
              <div className="px-6 py-3 border-b border-[var(--color-error-100)]">
                <h3 className="text-sm font-semibold text-[var(--color-error-700)] flex items-center gap-2">
                  <AlertTriangle className="w-4 h-4" />
                  {t('dashboard:new_dashboard.production_status.equipment_alerts')}
                </h3>
              </div>
              {equipmentAlerts.map((alert, index) =>
                renderAlertItem(alert, index, equipmentAlerts.length)
              )}
            </div>
          )}

          {/* Production Alerts Section */}
          {filteredProductionAlerts.length > 0 && (
            <div className="bg-[var(--color-warning-50)]">
              <div className="px-6 py-3 border-b border-[var(--color-warning-100)]">
                <h3 className="text-sm font-semibold text-[var(--color-warning-700)] flex items-center gap-2">
                  <AlertTriangle className="w-4 h-4" />
                  {t('dashboard:new_dashboard.production_status.production_alerts')}
                </h3>
              </div>
              {filteredProductionAlerts.map((alert, index) =>
                renderAlertItem(alert, index, filteredProductionAlerts.length)
              )}
            </div>
          )}

          {/* Late to Start Section */}
          {hasLate && (
            <div className="bg-[var(--color-error-50)]">
              <div className="px-6 py-3 border-b border-[var(--color-error-100)]">
                <h3 className="text-sm font-semibold text-[var(--color-error-700)] flex items-center gap-2">
                  <AlertTriangle className="w-4 h-4" />
                  {t('dashboard:new_dashboard.production_status.late_section')}
                </h3>
              </div>
              {lateToStartBatches.map((batch, index) =>
                renderBatchItem(batch, 'late', index, lateToStartBatches.length)
              )}
            </div>
          )}

          {/* Running Section */}
          {hasRunning && (
            <div className="bg-[var(--color-info-50)]">
              <div className="px-6 py-3 border-b border-[var(--color-info-100)]">
                <h3 className="text-sm font-semibold text-[var(--color-info-700)] flex items-center gap-2">
                  <Timer className="w-4 h-4" />
                  {t('dashboard:new_dashboard.production_status.running_section')}
                </h3>
              </div>
              {runningBatches.map((batch, index) =>
                renderBatchItem(batch, 'running', index, runningBatches.length)
              )}
            </div>
          )}

          {/* Pending Section */}
          {hasPending && (
            <div>
              <div className="px-6 py-3 border-b border-[var(--border-primary)] bg-[var(--bg-secondary)]">
                <h3 className="text-sm font-semibold text-[var(--text-secondary)] flex items-center gap-2">
                  <Clock className="w-4 h-4" />
                  {t('dashboard:new_dashboard.production_status.pending_section')}
                </h3>
              </div>
              {pendingBatches.map((batch, index) =>
                renderBatchItem(batch, 'pending', index, pendingBatches.length)
              )}
            </div>
          )}
        </div>
      ) : (
        /* Empty State */
        <div className="px-6 pb-6">
          <div className="flex items-center gap-3 p-4 rounded-lg bg-[var(--color-success-50)] border border-[var(--color-success-100)]">
            <CheckCircle2 className="w-6 h-6 text-[var(--color-success-600)]" />
            <p className="text-sm text-[var(--color-success-700)]">
              {t('dashboard:new_dashboard.production_status.all_clear')}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

export default ProductionStatusBlock;
