import React from 'react';
import { useTranslation } from 'react-i18next';
import { DollarSign, TrendingUp, TrendingDown, PieChart } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { AnalyticsChart, ChartSeries } from '../AnalyticsChart';
import { Button } from '../../../../ui';
import { useActiveBatches } from '../../../../../api/hooks/production';
import { useCurrentTenant } from '../../../../../stores/tenant.store';
import { useTenantCurrency } from '../../../../../hooks/useTenantCurrency';

interface ProductCostData {
  product: string;
  estimatedCost: number;
  actualCost: number;
  variance: number;
  variancePercent: number;
  units: number;
  costPerUnit: number;
}

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

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

  // Process batches to calculate cost per unit data
  const getProductCostData = (): ProductCostData[] => {
    const productMap = new Map<string, any>();

    batches.forEach(batch => {
      const key = batch.product_name;
      if (!productMap.has(key)) {
        productMap.set(key, {
          product: batch.product_name,
          estimatedCosts: [],
          actualCosts: [],
          quantities: []
        });
      }

      const data = productMap.get(key);
      if (batch.estimated_cost) data.estimatedCosts.push(batch.estimated_cost);
      if (batch.actual_cost) data.actualCosts.push(batch.actual_cost);
      if (batch.actual_quantity || batch.planned_quantity) {
        data.quantities.push(batch.actual_quantity || batch.planned_quantity);
      }
    });

    return Array.from(productMap.values()).map(data => {
      const avgEstimated = data.estimatedCosts.reduce((a: number, b: number) => a + b, 0) / (data.estimatedCosts.length || 1);
      const avgActual = data.actualCosts.reduce((a: number, b: number) => a + b, 0) / (data.actualCosts.length || 1);
      const totalUnits = data.quantities.reduce((a: number, b: number) => a + b, 0);
      const variance = avgActual - avgEstimated;
      const variancePercent = avgEstimated > 0 ? (variance / avgEstimated) * 100 : 0;
      const costPerUnit = totalUnits > 0 ? avgActual / totalUnits : avgActual;

      return {
        product: data.product,
        estimatedCost: avgEstimated,
        actualCost: avgActual,
        variance,
        variancePercent,
        units: totalUnits,
        costPerUnit
      };
    }).filter(item => item.actualCost > 0);
  };

  const productCostData = getProductCostData();
  const totalCosts = productCostData.reduce((sum, item) => sum + item.actualCost, 0);
  const averageCostPerUnit = productCostData.length > 0
    ? productCostData.reduce((sum, item) => sum + item.costPerUnit, 0) / productCostData.length
    : 0;

  // Create chart data for cost comparison
  const getCostComparisonChartData = (): ChartSeries[] => {
    if (productCostData.length === 0) return [];

    const estimatedData = productCostData.map(item => ({
      x: item.product,
      y: item.estimatedCost,
      label: item.product
    }));

    const actualData = productCostData.map(item => ({
      x: item.product,
      y: item.actualCost,
      label: item.product
    }));

    return [
      {
        id: 'estimated-cost',
        name: t('cost.estimated_cost'),
        type: 'bar',
        color: '#94a3b8',
        data: estimatedData
      },
      {
        id: 'actual-cost',
        name: t('cost.actual_cost'),
        type: 'bar',
        color: '#d97706',
        data: actualData
      }
    ];
  };

  // Create pie chart for cost distribution
  const getCostDistributionChartData = (): ChartSeries[] => {
    if (productCostData.length === 0) return [];

    const pieData = productCostData.map((item, index) => ({
      x: item.product,
      y: item.actualCost,
      label: item.product,
      color: getProductColor(index)
    }));

    return [
      {
        id: 'cost-distribution',
        name: t('cost.cost_distribution'),
        type: 'pie',
        color: '#d97706',
        data: pieData
      }
    ];
  };

  const getProductColor = (index: number): string => {
    const colors = ['#d97706', '#0284c7', '#16a34a', '#dc2626', '#7c3aed', '#0891b2'];
    return colors[index % colors.length];
  };

  const getVarianceStatus = (variancePercent: number) => {
    if (Math.abs(variancePercent) <= 5) return { color: 'text-green-600', status: 'on_target' };
    if (variancePercent > 5) return { color: 'text-red-600', status: 'over_budget' };
    return { color: 'text-blue-600', status: 'under_budget' };
  };

  return (
    <AnalyticsWidget
      title={t('cost.cost_per_unit_analysis')}
      subtitle={t('cost.estimated_vs_actual_costs')}
      icon={DollarSign}
      loading={isLoading}
      error={error?.message}
      actions={
        <Button variant="outline" size="sm">
          <PieChart className="w-4 h-4 mr-1" />
          {t('cost.view_breakdown')}
        </Button>
      }
    >
      <div className="space-y-4">
        {/* Overall Metrics */}
        <div className="grid grid-cols-2 gap-4">
          <div className="p-4 bg-[var(--bg-secondary)] rounded-lg text-center">
            <div className="flex items-center justify-center space-x-2 mb-2">
              <DollarSign className="w-5 h-5 text-[var(--color-primary)]" />
              <span className="text-lg font-bold text-[var(--text-primary)]">
                {currencySymbol}{averageCostPerUnit.toFixed(2)}
              </span>
            </div>
            <p className="text-sm text-[var(--text-secondary)]">{t('cost.average_cost_per_unit')}</p>
          </div>
          <div className="p-4 bg-[var(--bg-secondary)] rounded-lg text-center">
            <div className="flex items-center justify-center space-x-2 mb-2">
              <TrendingUp className="w-5 h-5 text-[var(--color-primary)]" />
              <span className="text-lg font-bold text-[var(--text-primary)]">
                {currencySymbol}{totalCosts.toFixed(0)}
              </span>
            </div>
            <p className="text-sm text-[var(--text-secondary)]">{t('cost.total_production_cost')}</p>
          </div>
        </div>

        {productCostData.length === 0 ? (
          <div className="text-center py-8 text-[var(--text-secondary)]">
            <DollarSign className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p className="text-sm">{t('cost.no_cost_data_available')}</p>
          </div>
        ) : (
          <>
            {/* Cost Comparison Chart */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('cost.estimated_vs_actual')}
              </h4>
              <AnalyticsChart
                series={getCostComparisonChartData()}
                height={200}
                showLegend={true}
                showGrid={true}
              />
            </div>

            {/* Product Cost Details */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('cost.product_cost_breakdown')}
              </h4>
              <div className="space-y-3 max-h-64 overflow-y-auto">
                {productCostData.map((item, index) => {
                  const varianceStatus = getVarianceStatus(item.variancePercent);
                  const VarianceIcon = item.variance >= 0 ? TrendingUp : TrendingDown;

                  return (
                    <div key={index} className="p-3 bg-[var(--bg-secondary)] rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center space-x-3">
                          <div
                            className="w-3 h-3 rounded-full"
                            style={{ backgroundColor: getProductColor(index) }}
                          />
                          <span className="font-medium text-[var(--text-primary)]">
                            {item.product}
                          </span>
                        </div>
                        <span className="text-lg font-bold text-[var(--text-primary)]">
                          {currencySymbol}{item.costPerUnit.toFixed(2)}
                        </span>
                      </div>

                      <div className="grid grid-cols-3 gap-3 text-sm">
                        <div>
                          <p className="text-[var(--text-secondary)]">{t('cost.estimated')}</p>
                          <p className="font-semibold text-[var(--text-primary)]">
                            {currencySymbol}{item.estimatedCost.toFixed(2)}
                          </p>
                        </div>
                        <div>
                          <p className="text-[var(--text-secondary)]">{t('cost.actual')}</p>
                          <p className="font-semibold text-[var(--text-primary)]">
                            {currencySymbol}{item.actualCost.toFixed(2)}
                          </p>
                        </div>
                        <div>
                          <p className="text-[var(--text-secondary)]">{t('cost.variance')}</p>
                          <div className={`flex items-center space-x-1 ${varianceStatus.color}`}>
                            <VarianceIcon className="w-3 h-3" />
                            <span className="font-semibold">
                              {item.variancePercent > 0 ? '+' : ''}{item.variancePercent.toFixed(1)}%
                            </span>
                          </div>
                        </div>
                      </div>

                      <div className="mt-2 pt-2 border-t border-[var(--border-primary)] text-xs text-[var(--text-tertiary)]">
                        {t('cost.units_produced')}: {item.units}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Cost Distribution Pie Chart */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('cost.cost_distribution')}
              </h4>
              <AnalyticsChart
                series={getCostDistributionChartData()}
                height={200}
                showLegend={true}
                showGrid={false}
              />
            </div>

            {/* Cost Optimization Insights */}
            <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
              <div className="flex items-start space-x-2">
                <DollarSign className="w-4 h-4 mt-0.5 text-blue-600" />
                <div>
                  <p className="text-sm font-medium text-blue-600">
                    {t('cost.optimization_opportunity')}
                  </p>
                  <p className="text-xs text-[var(--text-secondary)] mt-1">
                    {productCostData.some(item => item.variancePercent > 10)
                      ? t('cost.high_variance_detected')
                      : t('cost.costs_within_expected_range')
                    }
                  </p>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </AnalyticsWidget>
  );
};