import React from 'react';
import { useTranslation } from 'react-i18next';
import { AlertTriangle, Trash2, Target, TrendingDown } 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';
import { useTenantCurrency } from '../../../../../hooks/useTenantCurrency';

interface WasteSource {
  source: string;
  count: number;
  percentage: number;
  cost: number;
  severity: 'low' | 'medium' | 'high';
}

export const WasteDefectTrackerWidget: 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 || [];

  // Calculate waste and defect data from batches
  const getWasteData = () => {
    const totalUnits = batches.reduce((sum, batch) => sum + (batch.actual_quantity || batch.planned_quantity || 0), 0);
    const totalWaste = batches.reduce((sum, batch) => sum + (batch.waste_quantity || 0), 0);
    const totalDefects = batches.reduce((sum, batch) => sum + (batch.defect_quantity || 0), 0);

    const wastePercentage = totalUnits > 0 ? (totalWaste / totalUnits) * 100 : 0;
    const defectPercentage = totalUnits > 0 ? (totalDefects / totalUnits) * 100 : 0;

    return {
      totalUnits,
      totalWaste,
      totalDefects,
      wastePercentage,
      defectPercentage
    };
  };

  const wasteData = getWasteData();

  // Mock waste sources data (in real implementation, this would come from quality check defect types)
  const getWasteSources = (): WasteSource[] => {
    return [
      {
        source: t('quality.defects.burnt'),
        count: Math.round(wasteData.totalWaste * 0.35),
        percentage: 35,
        cost: 45.20,
        severity: 'high'
      },
      {
        source: t('quality.defects.misshapen'),
        count: Math.round(wasteData.totalWaste * 0.28),
        percentage: 28,
        cost: 32.15,
        severity: 'medium'
      },
      {
        source: t('quality.defects.underproofed'),
        count: Math.round(wasteData.totalWaste * 0.20),
        percentage: 20,
        cost: 28.90,
        severity: 'medium'
      },
      {
        source: t('quality.defects.temperature_issues'),
        count: Math.round(wasteData.totalWaste * 0.12),
        percentage: 12,
        cost: 18.70,
        severity: 'low'
      },
      {
        source: t('quality.defects.expired'),
        count: Math.round(wasteData.totalWaste * 0.05),
        percentage: 5,
        cost: 8.40,
        severity: 'low'
      }
    ].filter(source => source.count > 0);
  };

  const wasteSources = getWasteSources();
  const totalWasteCost = wasteSources.reduce((sum, source) => sum + source.cost, 0);

  // Create pie chart for waste sources
  const getWasteSourcesChartData = (): ChartSeries[] => {
    if (wasteSources.length === 0) return [];

    const colors = ['#dc2626', '#ea580c', '#d97706', '#ca8a04', '#65a30d'];
    const pieData = wasteSources.map((source, index) => ({
      x: source.source,
      y: source.count,
      label: source.source,
      color: colors[index % colors.length]
    }));

    return [
      {
        id: 'waste-sources',
        name: t('quality.waste_sources'),
        type: 'pie',
        color: '#dc2626',
        data: pieData
      }
    ];
  };

  // Create trend chart for waste over time
  const getWasteTrendChartData = (): ChartSeries[] => {
    const days = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];
    const wasteData = days.map((day, index) => ({
      x: day,
      y: Math.max(1, 8 - index + Math.random() * 3), // Decreasing trend with some variation
      label: day
    }));

    const defectData = days.map((day, index) => ({
      x: day,
      y: Math.max(0.5, 5 - index * 0.5 + Math.random() * 2),
      label: day
    }));

    return [
      {
        id: 'waste-trend',
        name: t('quality.waste_percentage'),
        type: 'line',
        color: '#dc2626',
        data: wasteData
      },
      {
        id: 'defect-trend',
        name: t('quality.defect_percentage'),
        type: 'line',
        color: '#ea580c',
        data: defectData
      }
    ];
  };

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

  const getWasteStatus = () => {
    const totalWastePercentage = wasteData.wastePercentage + wasteData.defectPercentage;
    if (totalWastePercentage <= 3) return { status: 'excellent', color: 'text-[var(--color-success)]', bgColor: 'bg-[var(--color-success)]/10 border border-[var(--color-success)]/20' };
    if (totalWastePercentage <= 5) return { status: 'good', color: 'text-[var(--color-info)]', bgColor: 'bg-[var(--color-info)]/10 border border-[var(--color-info)]/20' };
    if (totalWastePercentage <= 8) return { status: 'warning', color: 'text-[var(--color-warning)]', bgColor: 'bg-[var(--color-warning)]/10 border border-[var(--color-warning)]/20' };
    return { status: 'critical', color: 'text-[var(--color-error)]', bgColor: 'bg-[var(--color-error)]/10 border border-[var(--color-error)]/20' };
  };

  const wasteStatus = getWasteStatus();
  const totalWastePercentage = wasteData.wastePercentage + wasteData.defectPercentage;

  return (
    <AnalyticsWidget
      title={t('quality.waste_defect_tracker')}
      subtitle={t('quality.waste_sources_trends_costs')}
      icon={AlertTriangle}
      loading={isLoading}
      error={error?.message}
      actions={
        <Button variant="outline" size="sm">
          <Target className="w-4 h-4 mr-1" />
          {t('quality.actions.reduce_waste')}
        </Button>
      }
    >
      <div className="space-y-5">
        {/* Overall Waste Metrics */}
        <div className="grid grid-cols-3 gap-4">
          <div className="p-4 bg-[var(--color-error)]/10 border border-[var(--color-error)]/20 rounded-lg text-center hover:border-[var(--color-error)]/40 transition-colors">
            <div className="flex items-center justify-center space-x-2 mb-1">
              <Trash2 className="w-5 h-5 text-[var(--color-error)]" />
              <span className="text-2xl font-bold text-[var(--color-error)]">
                {totalWastePercentage.toFixed(1)}%
              </span>
            </div>
            <p className="text-xs text-[var(--text-secondary)] font-medium">{t('quality.total_waste')}</p>
          </div>
          <div className="p-4 bg-[var(--color-warning)]/10 border border-[var(--color-warning)]/20 rounded-lg text-center hover:border-[var(--color-warning)]/40 transition-colors">
            <div className="flex items-center justify-center space-x-2 mb-1">
              <AlertTriangle className="w-5 h-5 text-[var(--color-warning)]" />
              <span className="text-2xl font-bold text-[var(--color-warning)]">
                {wasteData.totalDefects}
              </span>
            </div>
            <p className="text-xs text-[var(--text-secondary)] font-medium">{t('quality.total_defects')}</p>
          </div>
          <div className="p-4 bg-[var(--color-success)]/10 border border-[var(--color-success)]/20 rounded-lg text-center hover:border-[var(--color-success)]/40 transition-colors">
            <div className="flex items-center justify-center space-x-2 mb-1">
              <TrendingDown className="w-5 h-5 text-[var(--color-success)]" />
              <span className="text-2xl font-bold text-[var(--color-success)]">
                {currencySymbol}{totalWasteCost.toFixed(0)}
              </span>
            </div>
            <p className="text-xs text-[var(--text-secondary)] font-medium">{t('cost.waste_cost')}</p>
          </div>
        </div>

        {/* Waste Status */}
        <div className={`p-4 rounded-lg ${wasteStatus.bgColor}`}>
          <div className="flex items-center space-x-2">
            <AlertTriangle className={`w-5 h-5 ${wasteStatus.color}`} />
            <span className={`text-sm font-semibold ${wasteStatus.color}`}>
              {t(`quality.status.${wasteStatus.status}`)}
            </span>
          </div>
        </div>

        {wasteSources.length === 0 ? (
          <div className="text-center py-8 text-[var(--text-secondary)]">
            <Target className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p className="text-sm">{t('quality.no_waste_data')}</p>
          </div>
        ) : (
          <>
            {/* Waste Sources Breakdown */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('quality.top_waste_sources')}
              </h4>
              <div className="space-y-2">
                {wasteSources.slice(0, 5).map((source, index) => (
                  <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="w-3 h-3 bg-red-500 rounded-full" />
                      <div>
                        <p className="text-sm font-medium text-[var(--text-primary)]">
                          {source.source}
                        </p>
                        <p className="text-xs text-[var(--text-secondary)]">
                          {source.count} {t('common.units')} • {currencySymbol}{source.cost.toFixed(2)}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <span className="text-sm font-semibold text-[var(--text-primary)]">
                        {source.percentage}%
                      </span>
                      <Badge variant={getSeverityBadgeVariant(source.severity)}>
                        {t(`quality.severity.${source.severity}`)}
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Waste Sources Pie Chart */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('quality.waste_distribution')}
              </h4>
              <AnalyticsChart
                series={getWasteSourcesChartData()}
                height={200}
                showLegend={true}
                showGrid={false}
              />
            </div>

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

            {/* Reduction Recommendations */}
            <div className="space-y-3">
              {wasteSources.filter(s => s.severity === 'high').length > 0 && (
                <div className="flex items-start space-x-3 p-4 bg-[var(--color-error)]/10 border border-[var(--color-error)]/20 rounded-lg">
                  <AlertTriangle className="w-5 h-5 mt-0.5 text-[var(--color-error)]" />
                  <div className="flex-1">
                    <p className="text-sm font-semibold text-[var(--color-error)] mb-1">
                      {t('quality.recommendations.high_waste_detected')}
                    </p>
                    <p className="text-xs text-[var(--text-secondary)]">
                      {t('quality.recommendations.check_temperature_timing')}
                    </p>
                  </div>
                </div>
              )}

              <div className="flex items-start space-x-3 p-4 bg-[var(--color-info)]/10 border border-[var(--color-info)]/20 rounded-lg">
                <Target className="w-5 h-5 mt-0.5 text-[var(--color-info)]" />
                <div className="flex-1">
                  <p className="text-sm font-semibold text-[var(--color-info)] mb-1">
                    {t('quality.recommendations.improvement_opportunity')}
                  </p>
                  <p className="text-xs text-[var(--text-secondary)]">
                    {totalWastePercentage > 5
                      ? t('quality.recommendations.reduce_waste_target', { target: '3%' })
                      : t('quality.recommendations.maintain_quality_standards')
                    }
                  </p>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </AnalyticsWidget>
  );
};