import React from 'react';
import { useTranslation } from 'react-i18next';
import { Zap, TrendingUp, TrendingDown, BarChart3, Target } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { AnalyticsChart, ChartSeries } from '../AnalyticsChart';
import { Button } from '../../../../ui';
import { useCurrentTenant } from '../../../../../stores/tenant.store';

interface EquipmentEfficiencyData {
  equipmentId: string;
  equipmentName: string;
  type: 'oven' | 'mixer' | 'proofer' | 'packaging';
  currentEfficiency: number;
  targetEfficiency: number;
  trend: 'up' | 'down' | 'stable';
  energyConsumption: number; // kWh
  productionOutput: number; // units per hour
  oee: number; // Overall Equipment Effectiveness
  availability: number;
  performance: number;
  quality: number;
  downtimeMinutes: number;
  weeklyData: Array<{
    day: string;
    efficiency: number;
    energyConsumption: number;
    output: number;
  }>;
}

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

  // Mock efficiency data - replace with real API call
  const efficiencyData: EquipmentEfficiencyData[] = [
    {
      equipmentId: '1',
      equipmentName: 'Horno Principal',
      type: 'oven',
      currentEfficiency: 94,
      targetEfficiency: 95,
      trend: 'up',
      energyConsumption: 45.2,
      productionOutput: 120,
      oee: 89,
      availability: 95,
      performance: 96,
      quality: 98,
      downtimeMinutes: 15,
      weeklyData: [
        { day: 'Lun', efficiency: 92, energyConsumption: 44, output: 118 },
        { day: 'Mar', efficiency: 93, energyConsumption: 45, output: 119 },
        { day: 'Mié', efficiency: 94, energyConsumption: 45.2, output: 120 },
        { day: 'Jue', efficiency: 94, energyConsumption: 45.1, output: 121 },
        { day: 'Vie', efficiency: 95, energyConsumption: 45.3, output: 122 },
        { day: 'Sáb', efficiency: 94, energyConsumption: 44.8, output: 119 },
        { day: 'Dom', efficiency: 93, energyConsumption: 44.5, output: 117 }
      ]
    },
    {
      equipmentId: '2',
      equipmentName: 'Mezcladora A',
      type: 'mixer',
      currentEfficiency: 87,
      targetEfficiency: 90,
      trend: 'down',
      energyConsumption: 12.5,
      productionOutput: 85,
      oee: 82,
      availability: 92,
      performance: 89,
      quality: 95,
      downtimeMinutes: 45,
      weeklyData: [
        { day: 'Lun', efficiency: 89, energyConsumption: 12, output: 88 },
        { day: 'Mar', efficiency: 88, energyConsumption: 12.2, output: 87 },
        { day: 'Mié', efficiency: 87, energyConsumption: 12.5, output: 85 },
        { day: 'Jue', efficiency: 86, energyConsumption: 12.8, output: 84 },
        { day: 'Vie', efficiency: 87, energyConsumption: 12.6, output: 86 },
        { day: 'Sáb', efficiency: 88, energyConsumption: 12.3, output: 87 },
        { day: 'Dom', efficiency: 87, energyConsumption: 12.4, output: 85 }
      ]
    },
    {
      equipmentId: '3',
      equipmentName: 'Cámara de Fermentación 1',
      type: 'proofer',
      currentEfficiency: 96,
      targetEfficiency: 95,
      trend: 'stable',
      energyConsumption: 8.3,
      productionOutput: 95,
      oee: 94,
      availability: 98,
      performance: 97,
      quality: 99,
      downtimeMinutes: 5,
      weeklyData: [
        { day: 'Lun', efficiency: 96, energyConsumption: 8.2, output: 94 },
        { day: 'Mar', efficiency: 96, energyConsumption: 8.3, output: 95 },
        { day: 'Mié', efficiency: 96, energyConsumption: 8.3, output: 95 },
        { day: 'Jue', efficiency: 97, energyConsumption: 8.4, output: 96 },
        { day: 'Vie', efficiency: 96, energyConsumption: 8.3, output: 95 },
        { day: 'Sáb', efficiency: 95, energyConsumption: 8.2, output: 94 },
        { day: 'Dom', efficiency: 96, energyConsumption: 8.3, output: 95 }
      ]
    }
  ];

  const getTrendIcon = (trend: EquipmentEfficiencyData['trend']) => {
    switch (trend) {
      case 'up': return TrendingUp;
      case 'down': return TrendingDown;
      case 'stable': return BarChart3;
      default: return BarChart3;
    }
  };

  const getTrendColor = (trend: EquipmentEfficiencyData['trend']) => {
    switch (trend) {
      case 'up': return 'text-green-600';
      case 'down': return 'text-red-600';
      case 'stable': return 'text-blue-600';
      default: return 'text-gray-600';
    }
  };

  const getEfficiencyStatus = (current: number, target: number) => {
    const percentage = (current / target) * 100;
    if (percentage >= 100) return { status: 'excellent', color: 'text-green-600', bgColor: 'bg-green-100 dark:bg-green-900/20' };
    if (percentage >= 90) return { status: 'good', color: 'text-blue-600', bgColor: 'bg-blue-100 dark:bg-blue-900/20' };
    if (percentage >= 80) return { status: 'warning', color: 'text-orange-600', bgColor: 'bg-orange-100 dark:bg-orange-900/20' };
    return { status: 'critical', color: 'text-red-600', bgColor: 'bg-red-100 dark:bg-red-900/20' };
  };

  // Calculate overall metrics
  const avgEfficiency = efficiencyData.reduce((sum, item) => sum + item.currentEfficiency, 0) / efficiencyData.length;
  const avgOEE = efficiencyData.reduce((sum, item) => sum + item.oee, 0) / efficiencyData.length;
  const totalEnergyConsumption = efficiencyData.reduce((sum, item) => sum + item.energyConsumption, 0);
  const totalDowntime = efficiencyData.reduce((sum, item) => sum + item.downtimeMinutes, 0);

  // Create efficiency comparison chart
  const getEfficiencyComparisonChartData = (): ChartSeries[] => {
    const currentData = efficiencyData.map(item => ({
      x: item.equipmentName,
      y: item.currentEfficiency,
      label: `${item.equipmentName}: ${item.currentEfficiency}%`
    }));

    const targetData = efficiencyData.map(item => ({
      x: item.equipmentName,
      y: item.targetEfficiency,
      label: `Target: ${item.targetEfficiency}%`
    }));

    return [
      {
        id: 'current-efficiency',
        name: t('equipment.efficiency.current'),
        type: 'bar',
        color: '#16a34a',
        data: currentData
      },
      {
        id: 'target-efficiency',
        name: t('equipment.efficiency.target'),
        type: 'bar',
        color: '#d97706',
        data: targetData
      }
    ];
  };

  // Create weekly efficiency trend chart
  const getWeeklyTrendChartData = (): ChartSeries[] => {
    return efficiencyData.map((equipment, index) => ({
      id: `weekly-${equipment.equipmentId}`,
      name: equipment.equipmentName,
      type: 'line',
      color: ['#16a34a', '#3b82f6', '#f59e0b'][index % 3],
      data: equipment.weeklyData.map(day => ({
        x: day.day,
        y: day.efficiency,
        label: `${day.day}: ${day.efficiency}%`
      }))
    }));
  };

  // Create OEE breakdown chart
  const getOEEBreakdownChartData = (): ChartSeries[] => {
    const avgAvailability = efficiencyData.reduce((sum, item) => sum + item.availability, 0) / efficiencyData.length;
    const avgPerformance = efficiencyData.reduce((sum, item) => sum + item.performance, 0) / efficiencyData.length;
    const avgQuality = efficiencyData.reduce((sum, item) => sum + item.quality, 0) / efficiencyData.length;

    return [
      {
        id: 'oee-breakdown',
        name: 'OEE Components',
        type: 'doughnut',
        color: '#3b82f6',
        data: [
          { x: t('equipment.oee.availability'), y: avgAvailability, label: `${t('equipment.oee.availability')}: ${avgAvailability.toFixed(1)}%` },
          { x: t('equipment.oee.performance'), y: avgPerformance, label: `${t('equipment.oee.performance')}: ${avgPerformance.toFixed(1)}%` },
          { x: t('equipment.oee.quality'), y: avgQuality, label: `${t('equipment.oee.quality')}: ${avgQuality.toFixed(1)}%` }
        ]
      }
    ];
  };

  return (
    <AnalyticsWidget
      title={t('equipment.efficiency.title')}
      subtitle={t('equipment.efficiency.subtitle')}
      icon={Zap}
      actions={
        <div className="flex space-x-2">
          <Button variant="outline" size="sm">
            <BarChart3 className="w-4 h-4 mr-1" />
            {t('equipment.efficiency.analyze')}
          </Button>
          <Button variant="primary" size="sm">
            <Target className="w-4 h-4 mr-1" />
            {t('equipment.efficiency.optimize')}
          </Button>
        </div>
      }
    >
      <div className="space-y-6">
        {/* Efficiency 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">
            <Zap className="w-8 h-8 mx-auto text-green-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{avgEfficiency.toFixed(1)}%</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.efficiency.average')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <Target className="w-8 h-8 mx-auto text-blue-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{avgOEE.toFixed(1)}%</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.oee.overall')}</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">kWh</span>
            </div>
            <p className="text-2xl font-bold text-[var(--text-primary)]">{totalEnergyConsumption.toFixed(1)}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.energy_consumption')}</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">min</span>
            </div>
            <p className="text-2xl font-bold text-[var(--text-primary)]">{totalDowntime}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.downtime.total')}</p>
          </div>
        </div>

        {/* Equipment Efficiency List */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3 flex items-center">
            <Zap className="w-4 h-4 mr-2" />
            {t('equipment.efficiency.by_equipment')}
          </h4>
          <div className="space-y-3">
            {efficiencyData.map((item) => {
              const TrendIcon = getTrendIcon(item.trend);
              const trendColor = getTrendColor(item.trend);
              const status = getEfficiencyStatus(item.currentEfficiency, item.targetEfficiency);

              return (
                <div key={item.equipmentId} className="p-4 bg-[var(--bg-secondary)] rounded-lg">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center space-x-3">
                      <Zap className="w-5 h-5 text-[var(--color-primary)]" />
                      <div>
                        <p className="font-medium text-[var(--text-primary)]">{item.equipmentName}</p>
                        <div className="flex items-center space-x-2 text-xs text-[var(--text-secondary)]">
                          <span>OEE: {item.oee}%</span>
                          <span>•</span>
                          <span>{item.energyConsumption} kWh</span>
                          <span>•</span>
                          <span>{item.productionOutput} {t('equipment.units_per_hour')}</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <TrendIcon className={`w-4 h-4 ${trendColor}`} />
                      <div className="text-right">
                        <div className="text-lg font-bold text-[var(--text-primary)]">
                          {item.currentEfficiency}%
                        </div>
                        <div className="text-xs text-[var(--text-secondary)]">
                          {t('equipment.efficiency.target')}: {item.targetEfficiency}%
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Progress bar */}
                  <div className="w-full bg-[var(--bg-tertiary)] rounded-full h-2 mb-3">
                    <div
                      className="bg-[var(--color-primary)] h-2 rounded-full transition-all duration-300"
                      style={{ width: `${(item.currentEfficiency / 100) * 100}%` }}
                    />
                  </div>

                  {/* OEE Components */}
                  <div className="grid grid-cols-3 gap-4 text-center">
                    <div>
                      <p className="text-lg font-semibold text-green-600">{item.availability}%</p>
                      <p className="text-xs text-[var(--text-secondary)]">{t('equipment.oee.availability')}</p>
                    </div>
                    <div>
                      <p className="text-lg font-semibold text-blue-600">{item.performance}%</p>
                      <p className="text-xs text-[var(--text-secondary)]">{t('equipment.oee.performance')}</p>
                    </div>
                    <div>
                      <p className="text-lg font-semibold text-orange-600">{item.quality}%</p>
                      <p className="text-xs text-[var(--text-secondary)]">{t('equipment.oee.quality')}</p>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Efficiency Charts */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Current vs Target Efficiency */}
          <div>
            <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
              {t('equipment.efficiency.current_vs_target')}
            </h4>
            <AnalyticsChart
              series={getEfficiencyComparisonChartData()}
              height={200}
              showLegend={true}
              showGrid={true}
            />
          </div>

          {/* OEE Breakdown */}
          <div>
            <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
              {t('equipment.oee.breakdown')}
            </h4>
            <AnalyticsChart
              series={getOEEBreakdownChartData()}
              height={200}
              showLegend={true}
              showGrid={false}
            />
          </div>
        </div>

        {/* Weekly Efficiency Trends */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
            {t('equipment.efficiency.weekly_trends')}
          </h4>
          <AnalyticsChart
            series={getWeeklyTrendChartData()}
            height={250}
            showLegend={true}
            showGrid={true}
          />
        </div>

        {/* Efficiency Recommendations */}
        <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
          <div className="flex items-start space-x-2">
            <Target className="w-5 h-5 text-blue-600 mt-0.5" />
            <div>
              <p className="text-sm font-medium text-blue-600">
                {t('equipment.efficiency.recommendations')}
              </p>
              <ul className="text-xs text-[var(--text-secondary)] mt-1 space-y-1">
                <li>• {t('equipment.efficiency.recommendation_1')}: Mezcladora A {t('equipment.efficiency.needs_maintenance')}</li>
                <li>• {t('equipment.efficiency.recommendation_2')}: {t('equipment.efficiency.optimize_energy_consumption')}</li>
                <li>• {t('equipment.efficiency.recommendation_3')}: {t('equipment.efficiency.schedule_preventive_maintenance')}</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </AnalyticsWidget>
  );
};