import React from 'react';
import { useTranslation } from 'react-i18next';
import { AlertCircle, Eye, Camera, CheckSquare } 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 DefectType {
  type: string;
  count: number;
  percentage: number;
  severity: 'low' | 'medium' | 'high';
  trend: 'up' | 'down' | 'stable';
  estimatedCost: number;
}

export const TopDefectTypesWidget: 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 defect data from batches
  const getDefectData = (): DefectType[] => {
    const totalDefects = batches.reduce((sum, batch) => sum + (batch.defect_quantity || 0), 0);

    if (totalDefects === 0) return [];

    // Mock defect type distribution (in real implementation, this would come from quality check defect_types)
    const defectTypes = [
      {
        type: 'burnt',
        count: Math.round(totalDefects * 0.32),
        percentage: 32,
        severity: 'high' as const,
        trend: 'down' as const,
        estimatedCost: 45.60
      },
      {
        type: 'underproofed',
        count: Math.round(totalDefects * 0.24),
        percentage: 24,
        severity: 'medium' as const,
        trend: 'stable' as const,
        estimatedCost: 28.90
      },
      {
        type: 'misshapen',
        count: Math.round(totalDefects * 0.19),
        percentage: 19,
        severity: 'medium' as const,
        trend: 'up' as const,
        estimatedCost: 22.40
      },
      {
        type: 'color_issues',
        count: Math.round(totalDefects * 0.15),
        percentage: 15,
        severity: 'low' as const,
        trend: 'stable' as const,
        estimatedCost: 15.20
      },
      {
        type: 'texture_problems',
        count: Math.round(totalDefects * 0.10),
        percentage: 10,
        severity: 'medium' as const,
        trend: 'down' as const,
        estimatedCost: 12.80
      }
    ].filter(defect => defect.count > 0);

    return defectTypes;
  };

  const defectData = getDefectData();
  const totalDefects = defectData.reduce((sum, defect) => sum + defect.count, 0);
  const totalDefectCost = defectData.reduce((sum, defect) => sum + defect.estimatedCost, 0);

  // Create defect distribution pie chart
  const getDefectDistributionChartData = (): ChartSeries[] => {
    if (defectData.length === 0) return [];

    const colors = ['#dc2626', '#ea580c', '#d97706', '#ca8a04', '#65a30d'];
    const pieData = defectData.map((defect, index) => ({
      x: t(`quality.defects.${defect.type}`),
      y: defect.count,
      label: t(`quality.defects.${defect.type}`),
      color: colors[index % colors.length]
    }));

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

  // Create defect trend over time
  const getDefectTrendChartData = (): ChartSeries[] => {
    if (defectData.length === 0) return [];

    const days = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];

    return defectData.slice(0, 3).map((defect, seriesIndex) => {
      const colors = ['#dc2626', '#ea580c', '#d97706'];
      const baseValue = defect.count / 7; // Average per day

      const trendData = days.map((day, index) => {
        let value = baseValue;
        // Apply trend
        if (defect.trend === 'up') value *= (1 + index * 0.05);
        else if (defect.trend === 'down') value *= (1 - index * 0.05);

        return {
          x: day,
          y: Math.max(0, value + (Math.random() - 0.5) * baseValue * 0.3),
          label: day
        };
      });

      return {
        id: `defect-trend-${defect.type}`,
        name: t(`quality.defects.${defect.type}`),
        type: 'line' as const,
        color: colors[seriesIndex],
        data: trendData
      };
    });
  };

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

  const getTrendIcon = (trend: DefectType['trend']) => {
    switch (trend) {
      case 'up': return '↗️';
      case 'down': return '↘️';
      case 'stable': return '➡️';
      default: return '➡️';
    }
  };

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

  return (
    <AnalyticsWidget
      title={t('quality.top_defect_types_24h')}
      subtitle={t('quality.defect_analysis_cost_impact')}
      icon={AlertCircle}
      loading={isLoading}
      error={error?.message}
      actions={
        <Button variant="outline" size="sm">
          <Eye className="w-4 h-4 mr-1" />
          {t('quality.actions.view_details')}
        </Button>
      }
    >
      <div className="space-y-4">
        {/* Overall Defect 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-1">
              <AlertCircle className="w-5 h-5 text-red-600" />
              <span className="text-2xl font-bold text-[var(--text-primary)]">
                {totalDefects}
              </span>
            </div>
            <p className="text-sm text-[var(--text-secondary)]">{t('quality.total_defects')}</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-1">
              <span className="text-2xl font-bold text-red-600">
                {currencySymbol}{totalDefectCost.toFixed(0)}
              </span>
            </div>
            <p className="text-sm text-[var(--text-secondary)]">{t('quality.estimated_cost')}</p>
          </div>
        </div>

        {defectData.length === 0 ? (
          <div className="text-center py-8 text-[var(--text-secondary)]">
            <CheckSquare className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
              {t('quality.no_defects_detected')}
            </h3>
            <p className="text-sm">{t('quality.excellent_quality_standards')}</p>
          </div>
        ) : (
          <>
            {/* Top Defect Types List */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('quality.defect_breakdown')}
              </h4>
              <div className="space-y-3 max-h-64 overflow-y-auto">
                {defectData.map((defect, 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-8 h-8 bg-red-100 dark:bg-red-900/20 rounded-lg flex items-center justify-center">
                        <span className="text-sm font-bold text-red-600">#{index + 1}</span>
                      </div>
                      <div>
                        <p className="font-medium text-[var(--text-primary)]">
                          {t(`quality.defects.${defect.type}`)}
                        </p>
                        <div className="flex items-center space-x-3 text-xs text-[var(--text-secondary)]">
                          <span>{defect.count} {t('quality.incidents')}</span>
                          <span>•</span>
                          <span>{currencySymbol}{defect.estimatedCost.toFixed(2)} {t('quality.cost')}</span>
                          <span className={getTrendColor(defect.trend)}>
                            {getTrendIcon(defect.trend)} {t(`quality.trend.${defect.trend}`)}
                          </span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <span className="text-lg font-bold text-[var(--text-primary)]">
                        {defect.percentage}%
                      </span>
                      <Badge variant={getSeverityBadgeVariant(defect.severity)}>
                        {t(`quality.severity.${defect.severity}`)}
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
            </div>

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

            {/* Defect Trends Over Time */}
            {defectData.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                  {t('quality.top_defects_weekly_trend')}
                </h4>
                <AnalyticsChart
                  series={getDefectTrendChartData()}
                  height={150}
                  showLegend={true}
                  showGrid={true}
                />
              </div>
            )}

            {/* Defect Prevention Insights */}
            <div className="space-y-2">
              {defectData.some(d => d.severity === 'high') && (
                <div className="flex items-start space-x-2 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
                  <AlertCircle className="w-4 h-4 mt-0.5 text-red-600" />
                  <div>
                    <p className="text-sm font-medium text-red-600">
                      {t('quality.recommendations.critical_defects')}
                    </p>
                    <p className="text-xs text-[var(--text-secondary)] mt-1">
                      {t('quality.recommendations.immediate_action_required')}
                    </p>
                  </div>
                </div>
              )}

              <div className="flex items-start space-x-2 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                <Camera className="w-4 h-4 mt-0.5 text-blue-600" />
                <div>
                  <p className="text-sm font-medium text-blue-600">
                    {t('quality.recommendations.documentation')}
                  </p>
                  <p className="text-xs text-[var(--text-secondary)] mt-1">
                    {t('quality.recommendations.photo_documentation_helps')}
                  </p>
                </div>
              </div>
            </div>

            {/* Action Items */}
            <div className="pt-3 border-t border-[var(--border-primary)]">
              <h5 className="text-sm font-medium text-[var(--text-primary)] mb-2">
                {t('quality.recommended_actions')}
              </h5>
              <div className="space-y-1 text-xs text-[var(--text-secondary)]">
                {defectData[0] && (
                  <p>• {t('quality.actions.focus_on')} {t(`quality.defects.${defectData[0].type}`).toLowerCase()}</p>
                )}
                {defectData.some(d => d.trend === 'up') && (
                  <p>• {t('quality.actions.investigate_increasing_defects')}</p>
                )}
                <p>• {t('quality.actions.review_process_controls')}</p>
              </div>
            </div>
          </>
        )}
      </div>
    </AnalyticsWidget>
  );
};