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

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

  const { data: dashboard, isLoading, error } = useProductionDashboard(tenantId);

  // Mock historical data for the chart (in a real implementation, this would come from an analytics API)
  const getHistoricalCompletionData = (): ChartSeries[] => {
    const mockData = [
      { x: 'Lun', y: 92, label: 'Lunes' },
      { x: 'Mar', y: 89, label: 'Martes' },
      { x: 'Mié', y: 95, label: 'Miércoles' },
      { x: 'Jue', y: 87, label: 'Jueves' },
      { x: 'Vie', y: 94, label: 'Viernes' },
      { x: 'Sáb', y: 98, label: 'Sábado' },
      { x: 'Dom', y: dashboard?.on_time_completion_rate || 91, label: 'Domingo' },
    ];

    return [
      {
        id: 'completion-rate',
        name: t('stats.on_time_completion'),
        type: 'line',
        color: '#10b981',
        data: mockData
      }
    ];
  };

  const currentRate = dashboard?.on_time_completion_rate || 0;
  const targetRate = 95; // Target completion rate
  const weekAverage = 93; // Mock week average
  const trend = currentRate - weekAverage;

  const getCompletionRateStatus = (rate: number) => {
    if (rate >= 95) return { color: 'text-green-600', icon: TrendingUp, status: 'excellent' };
    if (rate >= 90) return { color: 'text-blue-600', icon: TrendingUp, status: 'good' };
    if (rate >= 85) return { color: 'text-orange-600', icon: TrendingDown, status: 'warning' };
    return { color: 'text-red-600', icon: TrendingDown, status: 'critical' };
  };

  const rateStatus = getCompletionRateStatus(currentRate);
  const RateIcon = rateStatus.icon;

  const getPerformanceInsight = () => {
    if (currentRate >= targetRate) {
      return {
        message: t('insights.on_time_excellent'),
        color: 'text-green-600',
        bgColor: 'bg-green-50 dark:bg-green-900/20'
      };
    } else if (currentRate >= 90) {
      return {
        message: t('insights.on_time_good_room_improvement'),
        color: 'text-blue-600',
        bgColor: 'bg-blue-50 dark:bg-blue-900/20'
      };
    } else if (currentRate >= 85) {
      return {
        message: t('insights.on_time_needs_attention'),
        color: 'text-orange-600',
        bgColor: 'bg-orange-50 dark:bg-orange-900/20'
      };
    } else {
      return {
        message: t('insights.on_time_critical_delays'),
        color: 'text-red-600',
        bgColor: 'bg-red-50 dark:bg-red-900/20'
      };
    }
  };

  const insight = getPerformanceInsight();

  return (
    <AnalyticsWidget
      title={t('stats.on_time_completion_rate')}
      subtitle={t('insights.on_time_vs_planned')}
      icon={Clock}
      loading={isLoading}
      error={error?.message}
      actions={
        <Button variant="outline" size="sm">
          <Target className="w-4 h-4 mr-1" />
          {t('actions.analyze_delays')}
        </Button>
      }
    >
      <div className="space-y-4">
        {/* Current Rate Display */}
        <div className="text-center">
          <div className="flex items-center justify-center space-x-2 mb-2">
            <RateIcon className={`w-6 h-6 ${rateStatus.color}`} />
            <span className="text-3xl font-bold text-[var(--text-primary)]">
              {currentRate.toFixed(1)}%
            </span>
          </div>
          <div className="flex items-center justify-center space-x-4 text-sm">
            <div className={`flex items-center space-x-1 ${trend >= 0 ? 'text-green-600' : 'text-red-600'}`}>
              {trend >= 0 ? (
                <TrendingUp className="w-4 h-4" />
              ) : (
                <TrendingDown className="w-4 h-4" />
              )}
              <span>{Math.abs(trend).toFixed(1)}% {t('insights.vs_week_avg')}</span>
            </div>
            <div className="text-[var(--text-secondary)]">
              {t('insights.target')}: {targetRate}%
            </div>
          </div>
        </div>

        {/* Progress towards target */}
        <div className="p-3 bg-[var(--bg-secondary)] rounded-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm text-[var(--text-secondary)]">{t('insights.progress_to_target')}</span>
            <span className="text-sm font-medium text-[var(--text-primary)]">
              {Math.min(currentRate, targetRate).toFixed(1)}% / {targetRate}%
            </span>
          </div>
          <div className="w-full bg-[var(--bg-tertiary)] rounded-full h-2">
            <div
              className={`h-2 rounded-full transition-all ${
                currentRate >= targetRate ? 'bg-green-500' :
                currentRate >= 90 ? 'bg-blue-500' :
                currentRate >= 85 ? 'bg-orange-500' : 'bg-red-500'
              }`}
              style={{ width: `${Math.min((currentRate / targetRate) * 100, 100)}%` }}
            />
          </div>
        </div>

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

        {/* Performance Insight */}
        <div className={`p-3 rounded-lg ${insight.bgColor}`}>
          <div className="flex items-start space-x-2">
            <Clock className={`w-4 h-4 mt-0.5 ${insight.color}`} />
            <div>
              <p className={`text-sm font-medium ${insight.color}`}>
                {t('insights.performance_insight')}
              </p>
              <p className="text-sm text-[var(--text-secondary)] mt-1">
                {insight.message}
              </p>
            </div>
          </div>
        </div>

        {/* Key Metrics */}
        <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-[var(--text-primary)]">
              {Math.round(currentRate * 0.85)}
            </p>
            <p className="text-xs text-[var(--text-secondary)]">{t('insights.batches_on_time')}</p>
          </div>
          <div className="p-3 bg-[var(--bg-secondary)] rounded-lg">
            <p className="text-lg font-bold text-[var(--text-primary)]">
              {Math.round((100 - currentRate) * 0.15)}
            </p>
            <p className="text-xs text-[var(--text-secondary)]">{t('insights.batches_delayed')}</p>
          </div>
          <div className="p-3 bg-[var(--bg-secondary)] rounded-lg">
            <p className="text-lg font-bold text-[var(--text-primary)]">
              {Math.round(12 * (100 - currentRate) / 100)}
            </p>
            <p className="text-xs text-[var(--text-secondary)]">{t('insights.avg_delay_minutes')}</p>
          </div>
        </div>
      </div>
    </AnalyticsWidget>
  );
};