import React from 'react';
import { useTranslation } from 'react-i18next';
import { Target, TrendingUp, Award, BarChart3 } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { AnalyticsChart, ChartSeries } from '../AnalyticsChart';
import { Button, Badge } from '../../../../ui';
import { useActiveBatches } from '../../../../../api/hooks/production';
import { useCurrentTenant } from '../../../../../stores/tenant.store';

interface ProductYieldData {
  product: string;
  averageYield: number;
  bestYield: number;
  worstYield: number;
  batchCount: number;
  trend: 'up' | 'down' | 'stable';
  performance: 'excellent' | 'good' | 'average' | 'poor';
}

export const YieldPerformanceWidget: React.FC = () => {
  const { t } = useTranslation('production');
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  const { data: batchesData, isLoading, error } = useActiveBatches(tenantId);
  const batches = batchesData?.batches || [];

  // Calculate yield data from batches
  const getProductYieldData = (): ProductYieldData[] => {
    const productMap = new Map<string, number[]>();

    batches.forEach(batch => {
      if (batch.yield_percentage) {
        const product = batch.product_name;
        if (!productMap.has(product)) {
          productMap.set(product, []);
        }
        productMap.get(product)!.push(batch.yield_percentage);
      }
    });

    return Array.from(productMap.entries()).map(([product, yields]) => {
      const averageYield = yields.reduce((sum, yieldValue) => sum + yieldValue, 0) / yields.length;
      const bestYield = Math.max(...yields);
      const worstYield = Math.min(...yields);

      // Simulate trend calculation (in real implementation, this would compare with historical data)
      const trend: 'up' | 'down' | 'stable' =
        averageYield > 92 ? 'up' :
        averageYield < 88 ? 'down' : 'stable';

      const performance: 'excellent' | 'good' | 'average' | 'poor' =
        averageYield >= 95 ? 'excellent' :
        averageYield >= 90 ? 'good' :
        averageYield >= 85 ? 'average' : 'poor';

      return {
        product,
        averageYield,
        bestYield,
        worstYield,
        batchCount: yields.length,
        trend,
        performance
      };
    }).sort((a, b) => b.averageYield - a.averageYield);
  };

  const productYieldData = getProductYieldData();
  const overallYield = productYieldData.length > 0
    ? productYieldData.reduce((sum, item) => sum + item.averageYield, 0) / productYieldData.length
    : 0;

  // Create yield comparison chart
  const getYieldComparisonChartData = (): ChartSeries[] => {
    if (productYieldData.length === 0) return [];

    const averageData = productYieldData.map(item => ({
      x: item.product,
      y: item.averageYield,
      label: item.product
    }));

    const bestData = productYieldData.map(item => ({
      x: item.product,
      y: item.bestYield,
      label: item.product
    }));

    return [
      {
        id: 'average-yield',
        name: t('stats.average_yield'),
        type: 'bar',
        color: '#d97706',
        data: averageData
      },
      {
        id: 'best-yield',
        name: t('stats.best_yield'),
        type: 'bar',
        color: '#16a34a',
        data: bestData
      }
    ];
  };

  // Create yield trend over time
  const getYieldTrendChartData = (): ChartSeries[] => {
    const days = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];
    const trendData = days.map((day, index) => ({
      x: day,
      y: Math.max(85, 90 + index * 0.5 + Math.random() * 3), // Slightly improving trend
      label: day
    }));

    return [
      {
        id: 'yield-trend',
        name: t('stats.yield_trend'),
        type: 'line',
        color: '#16a34a',
        data: trendData
      }
    ];
  };

  const getPerformanceBadgeVariant = (performance: ProductYieldData['performance']) => {
    switch (performance) {
      case 'excellent': return 'success';
      case 'good': return 'info';
      case 'average': return 'warning';
      case 'poor': return 'error';
      default: return 'default';
    }
  };

  const getTrendIcon = (trend: ProductYieldData['trend']) => {
    switch (trend) {
      case 'up': return TrendingUp;
      case 'down': return TrendingUp; // We'll rotate it in CSS for down
      case 'stable': return BarChart3;
      default: return BarChart3;
    }
  };

  const getTrendColor = (trend: ProductYieldData['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 getYieldStatus = () => {
    if (overallYield >= 95) return { status: 'excellent', color: 'text-green-600', bgColor: 'bg-green-100 dark:bg-green-900/20' };
    if (overallYield >= 90) return { status: 'good', color: 'text-blue-600', bgColor: 'bg-blue-100 dark:bg-blue-900/20' };
    if (overallYield >= 85) return { status: 'average', color: 'text-orange-600', bgColor: 'bg-orange-100 dark:bg-orange-900/20' };
    return { status: 'poor', color: 'text-red-600', bgColor: 'bg-red-100 dark:bg-red-900/20' };
  };

  const yieldStatus = getYieldStatus();

  return (
    <AnalyticsWidget
      title={t('stats.yield_performance_leaderboard')}
      subtitle={t('stats.product_yield_rankings_trends')}
      icon={Award}
      loading={isLoading}
      error={error?.message}
      actions={
        <Button variant="outline" size="sm">
          <Target className="w-4 h-4 mr-1" />
          {t('actions.optimize_yields')}
        </Button>
      }
    >
      <div className="space-y-4">
        {/* Overall Yield Status */}
        <div className="text-center">
          <div className="flex items-center justify-center space-x-2 mb-2">
            <Award className={`w-6 h-6 ${yieldStatus.color}`} />
            <span className="text-3xl font-bold text-[var(--text-primary)]">
              {overallYield.toFixed(1)}%
            </span>
          </div>
          <div className={`inline-flex items-center space-x-2 px-3 py-1 rounded-full text-sm ${yieldStatus.bgColor}`}>
            <span className={yieldStatus.color}>
              {t(`performance.${yieldStatus.status}`)}
            </span>
          </div>
        </div>

        {productYieldData.length === 0 ? (
          <div className="text-center py-8 text-[var(--text-secondary)]">
            <Award className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p className="text-sm">{t('stats.no_yield_data')}</p>
          </div>
        ) : (
          <>
            {/* Yield Leaderboard */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3 flex items-center">
                <Award className="w-4 h-4 mr-2" />
                {t('stats.product_leaderboard')}
              </h4>
              <div className="space-y-2 max-h-64 overflow-y-auto">
                {productYieldData.map((item, index) => {
                  const TrendIcon = getTrendIcon(item.trend);
                  const trendColor = getTrendColor(item.trend);

                  return (
                    <div key={index} className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                      <div className="flex items-center space-x-3">
                        <div className="flex items-center justify-center w-6 h-6 bg-[var(--color-primary)]/10 rounded-full text-xs font-bold text-[var(--color-primary)]">
                          {index + 1}
                        </div>
                        <div>
                          <p className="font-medium text-[var(--text-primary)]">
                            {item.product}
                          </p>
                          <div className="flex items-center space-x-2 text-xs text-[var(--text-secondary)]">
                            <span>{item.batchCount} {t('stats.batches')}</span>
                            <span>•</span>
                            <span>{item.bestYield.toFixed(1)}% {t('stats.best')}</span>
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <div className={`flex items-center space-x-1 ${trendColor}`}>
                          <TrendIcon
                            className={`w-3 h-3 ${item.trend === 'down' ? 'transform rotate-180' : ''}`}
                          />
                        </div>
                        <div className="text-right">
                          <div className="text-lg font-bold text-[var(--text-primary)]">
                            {item.averageYield.toFixed(1)}%
                          </div>
                          <Badge variant={getPerformanceBadgeVariant(item.performance)} className="text-xs">
                            {t(`performance.${item.performance}`)}
                          </Badge>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Yield Comparison Chart */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('stats.yield_comparison')}
              </h4>
              <AnalyticsChart
                series={getYieldComparisonChartData()}
                height={200}
                showLegend={true}
                showGrid={true}
              />
            </div>

            {/* Weekly Yield Trend */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('stats.weekly_yield_trend')}
              </h4>
              <AnalyticsChart
                series={getYieldTrendChartData()}
                height={150}
                showLegend={false}
                showGrid={true}
              />
            </div>

            {/* Yield Insights */}
            <div className="grid grid-cols-3 gap-3 text-center">
              <div className="p-3 bg-[var(--bg-secondary)] rounded-lg">
                <p className="text-lg font-bold text-green-600">
                  {productYieldData.filter(p => p.performance === 'excellent').length}
                </p>
                <p className="text-xs text-[var(--text-secondary)]">{t('performance.excellent')}</p>
              </div>
              <div className="p-3 bg-[var(--bg-secondary)] rounded-lg">
                <p className="text-lg font-bold text-blue-600">
                  {productYieldData.filter(p => p.performance === 'good').length}
                </p>
                <p className="text-xs text-[var(--text-secondary)]">{t('performance.good')}</p>
              </div>
              <div className="p-3 bg-[var(--bg-secondary)] rounded-lg">
                <p className="text-lg font-bold text-orange-600">
                  {productYieldData.filter(p => p.performance === 'average' || p.performance === 'poor').length}
                </p>
                <p className="text-xs text-[var(--text-secondary)]">{t('performance.needs_improvement')}</p>
              </div>
            </div>

            {/* Improvement Recommendations */}
            <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
              <div className="flex items-start space-x-2">
                <Target className="w-4 h-4 mt-0.5 text-blue-600" />
                <div>
                  <p className="text-sm font-medium text-blue-600">
                    {t('recommendations.yield_improvement')}
                  </p>
                  <p className="text-xs text-[var(--text-secondary)] mt-1">
                    {overallYield < 90
                      ? t('recommendations.focus_on_low_performers')
                      : t('recommendations.maintain_high_standards')
                    }
                  </p>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </AnalyticsWidget>
  );
};