import React from 'react';
import { useTranslation } from 'react-i18next';
import { Star, TrendingUp, TrendingDown, Award } 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';

export const QualityScoreTrendsWidget: 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 quality score data
  const getQualityData = () => {
    const qualityScores = batches
      .filter(batch => batch.quality_score)
      .map(batch => batch.quality_score!);

    if (qualityScores.length === 0) {
      return {
        averageScore: 0,
        totalChecks: 0,
        passRate: 0,
        trend: 0
      };
    }

    const averageScore = qualityScores.reduce((sum, score) => sum + score, 0) / qualityScores.length;
    const totalChecks = qualityScores.length;
    const passRate = (qualityScores.filter(score => score >= 7).length / totalChecks) * 100;

    // Mock trend calculation (would be compared with previous period in real implementation)
    const trend = 2.3; // +2.3 points vs last week

    return {
      averageScore,
      totalChecks,
      passRate,
      trend
    };
  };

  const qualityData = getQualityData();

  // Create daily quality trend chart
  const getQualityTrendChartData = (): ChartSeries[] => {
    const days = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];
    const scores = days.map((day, index) => ({
      x: day,
      y: Math.max(6, 8.5 + Math.sin(index) * 0.8 + (Math.random() - 0.5) * 0.5),
      label: day
    }));

    return [
      {
        id: 'quality-trend',
        name: t('quality.daily_quality_score'),
        type: 'line',
        color: 'var(--color-success)',
        data: scores
      }
    ];
  };

  // Create quality distribution chart
  const getQualityDistributionChartData = (): ChartSeries[] => {
    // Mock quality score distribution
    const distribution = [
      { range: '9-10', count: Math.round(qualityData.totalChecks * 0.35), label: t('quality.excellent') },
      { range: '8-9', count: Math.round(qualityData.totalChecks * 0.30), label: t('quality.good') },
      { range: '7-8', count: Math.round(qualityData.totalChecks * 0.20), label: t('quality.acceptable') },
      { range: '6-7', count: Math.round(qualityData.totalChecks * 0.10), label: t('quality.poor') },
      { range: '<6', count: Math.round(qualityData.totalChecks * 0.05), label: t('quality.failed') }
    ].filter(item => item.count > 0);

    return [
      {
        id: 'quality-distribution',
        name: t('quality.score_distribution'),
        type: 'bar',
        color: 'var(--color-primary)',
        data: distribution.map(item => ({
          x: item.range,
          y: item.count,
          label: item.label
        }))
      }
    ];
  };

  const getScoreColor = (score: number) => {
    if (score >= 9) return 'text-[var(--color-success)]';
    if (score >= 8) return 'text-[var(--color-info)]';
    if (score >= 7) return 'text-[var(--color-warning)]';
    return 'text-[var(--color-error)]';
  };

  const getScoreStatus = (score: number) => {
    if (score >= 9) return { status: 'excellent', bgColor: 'bg-[var(--color-success)]/10 border border-[var(--color-success)]/20' };
    if (score >= 8) return { status: 'good', bgColor: 'bg-[var(--color-info)]/10 border border-[var(--color-info)]/20' };
    if (score >= 7) return { status: 'acceptable', bgColor: 'bg-[var(--color-warning)]/10 border border-[var(--color-warning)]/20' };
    return { status: 'needs_improvement', bgColor: 'bg-[var(--color-error)]/10 border border-[var(--color-error)]/20' };
  };

  const scoreStatus = getScoreStatus(qualityData.averageScore);
  const TrendIcon = qualityData.trend >= 0 ? TrendingUp : TrendingDown;

  return (
    <AnalyticsWidget
      title={t('quality.recent_quality_scores')}
      subtitle={t('quality.daily_average_quality_trends')}
      icon={Star}
      loading={isLoading}
      error={error?.message}
      actions={
        <Button variant="outline" size="sm">
          <Award className="w-4 h-4 mr-1" />
          {t('quality.actions.view_trends')}
        </Button>
      }
    >
      <div className="space-y-5">
        {/* Quality Score Display */}
        <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
          <div className="flex items-center justify-center space-x-3 mb-3">
            <Star className={`w-8 h-8 fill-current ${getScoreColor(qualityData.averageScore)}`} />
            <span className="text-4xl font-bold text-[var(--text-primary)]">
              {qualityData.averageScore.toFixed(1)}
            </span>
            <span className="text-xl text-[var(--text-secondary)] font-medium">/10</span>
          </div>
          <div className={`inline-flex items-center space-x-2 px-4 py-1.5 rounded-full text-sm font-medium ${scoreStatus.bgColor}`}>
            <span className={getScoreColor(qualityData.averageScore)}>
              {t(`quality.${scoreStatus.status}`)}
            </span>
          </div>
          <div className="flex items-center justify-center space-x-1.5 mt-3 pt-3 border-t border-[var(--border-secondary)]">
            <TrendIcon className={`w-4 h-4 ${qualityData.trend >= 0 ? 'text-[var(--color-success)]' : 'text-[var(--color-error)]'}`} />
            <span className={`text-sm font-semibold ${qualityData.trend >= 0 ? 'text-[var(--color-success)]' : 'text-[var(--color-error)]'}`}>
              {qualityData.trend > 0 ? '+' : ''}{qualityData.trend.toFixed(1)} {t('quality.vs_last_week')}
            </span>
          </div>
        </div>

        {/* Key Metrics */}
        <div className="grid grid-cols-2 gap-4">
          <div className="p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] text-center hover:border-[var(--border-focus)] transition-colors">
            <div className="text-3xl font-bold text-[var(--text-primary)] mb-1">
              {qualityData.totalChecks}
            </div>
            <p className="text-sm text-[var(--text-secondary)] font-medium">{t('stats.total_checks')}</p>
          </div>
          <div className="p-4 bg-[var(--color-success)]/10 rounded-lg border border-[var(--color-success)]/20 text-center hover:border-[var(--color-success)]/40 transition-colors">
            <div className="text-3xl font-bold text-[var(--color-success)] mb-1">
              {qualityData.passRate.toFixed(1)}%
            </div>
            <p className="text-sm text-[var(--text-secondary)] font-medium">{t('stats.pass_rate')}</p>
          </div>
        </div>

        {qualityData.totalChecks === 0 ? (
          <div className="text-center py-8 text-[var(--text-secondary)]">
            <Star className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p className="text-sm">{t('quality.no_quality_data')}</p>
          </div>
        ) : (
          <>
            {/* Weekly Quality Trend */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('quality.weekly_quality_trends')}
              </h4>
              <AnalyticsChart
                series={getQualityTrendChartData()}
                height={150}
                showLegend={false}
                showGrid={true}
              />
            </div>

            {/* Quality Score Distribution */}
            <div>
              <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
                {t('quality.score_distribution')}
              </h4>
              <AnalyticsChart
                series={getQualityDistributionChartData()}
                height={180}
                showLegend={false}
                showGrid={true}
              />
            </div>

            {/* Quality Insights */}
            <div className="grid grid-cols-3 gap-3 text-center">
              <div className="p-3 bg-[var(--color-success)]/10 rounded-lg border border-[var(--color-success)]/20">
                <p className="text-2xl font-bold text-[var(--color-success)] mb-1">
                  {Math.round(qualityData.totalChecks * 0.35)}
                </p>
                <p className="text-xs text-[var(--text-secondary)] font-medium">{t('quality.excellent_scores')}</p>
              </div>
              <div className="p-3 bg-[var(--color-info)]/10 rounded-lg border border-[var(--color-info)]/20">
                <p className="text-2xl font-bold text-[var(--color-info)] mb-1">
                  {Math.round(qualityData.totalChecks * 0.30)}
                </p>
                <p className="text-xs text-[var(--text-secondary)] font-medium">{t('quality.good_scores')}</p>
              </div>
              <div className="p-3 bg-[var(--color-error)]/10 rounded-lg border border-[var(--color-error)]/20">
                <p className="text-2xl font-bold text-[var(--color-error)] mb-1">
                  {Math.round(qualityData.totalChecks * 0.15)}
                </p>
                <p className="text-xs text-[var(--text-secondary)] font-medium">{t('quality.needs_improvement')}</p>
              </div>
            </div>

            {/* Quality Recommendations */}
            {qualityData.averageScore < 8 && (
              <div className="p-4 bg-[var(--color-warning)]/10 border border-[var(--color-warning)]/20 rounded-lg">
                <div className="flex items-start space-x-3">
                  <Star className="w-5 h-5 mt-0.5 text-[var(--color-warning)]" />
                  <div className="flex-1">
                    <p className="text-sm font-semibold text-[var(--color-warning)] mb-1">
                      {t('quality.recommendations.improve_quality')}
                    </p>
                    <p className="text-xs text-[var(--text-secondary)]">
                      {t('quality.recommendations.focus_consistency')}
                    </p>
                  </div>
                </div>
              </div>
            )}

            {qualityData.averageScore >= 9 && (
              <div className="p-4 bg-[var(--color-success)]/10 border border-[var(--color-success)]/20 rounded-lg">
                <div className="flex items-start space-x-3">
                  <Award className="w-5 h-5 mt-0.5 text-[var(--color-success)]" />
                  <div className="flex-1">
                    <p className="text-sm font-semibold text-[var(--color-success)] mb-1">
                      {t('quality.recommendations.excellent_quality')}
                    </p>
                    <p className="text-xs text-[var(--text-secondary)]">
                      {t('quality.recommendations.maintain_standards')}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </AnalyticsWidget>
  );
};