import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  RotateCcw,
  Sparkles,
  Calendar,
  Settings,
  TrendingUp,
  Sun,
  Box,
  Zap,
  Info
} from 'lucide-react';
import { EditViewModal, EditViewModalAction, EditViewModalSection } from '../../ui/EditViewModal/EditViewModal';
import { Button } from '../../ui/Button';
import { IngredientResponse } from '../../../api/types/inventory';
import { TrainedModelResponse, SingleProductTrainingRequest } from '../../../api/types/training';

interface RetrainModelModalProps {
  isOpen: boolean;
  onClose: () => void;
  ingredient: IngredientResponse;
  currentModel?: TrainedModelResponse | null;
  onRetrain: (settings: SingleProductTrainingRequest) => Promise<void>;
  isLoading?: boolean;
}

type RetrainMode = 'quick' | 'preset' | 'advanced';

interface TrainingPreset {
  id: string;
  name: string;
  description: string;
  icon: typeof Sparkles;
  settings: Partial<SingleProductTrainingRequest>;
  recommended?: boolean;
}

export const RetrainModelModal: React.FC<RetrainModelModalProps> = ({
  isOpen,
  onClose,
  ingredient,
  currentModel,
  onRetrain,
  isLoading = false
}) => {
  const { t } = useTranslation(['models', 'common']);
  const [mode, setMode] = useState<RetrainMode>('quick');
  const [selectedPreset, setSelectedPreset] = useState<string>('standard');
  const [advancedSettings, setAdvancedSettings] = useState<SingleProductTrainingRequest>({
    seasonality_mode: 'additive',
    daily_seasonality: true,
    weekly_seasonality: true,
    yearly_seasonality: false,
  });

  // Define training presets - memoized to prevent recreation
  const presets: TrainingPreset[] = React.useMemo(() => [
    {
      id: 'standard',
      name: t('models:presets.standard.name', 'Panadería Estándar'),
      description: t('models:presets.standard.description', 'Recomendado para productos con patrones semanales y ciclos diarios. Ideal para pan y productos horneados diarios.'),
      icon: TrendingUp,
      settings: {
        seasonality_mode: 'additive',
        daily_seasonality: true,
        weekly_seasonality: true,
        yearly_seasonality: false,
      },
      recommended: true
    },
    {
      id: 'seasonal',
      name: t('models:presets.seasonal.name', 'Productos Estacionales'),
      description: t('models:presets.seasonal.description', 'Para productos con demanda estacional o de temporada. Incluye patrones anuales para festividades y eventos especiales.'),
      icon: Sun,
      settings: {
        seasonality_mode: 'additive',
        daily_seasonality: true,
        weekly_seasonality: true,
        yearly_seasonality: true,
      }
    },
    {
      id: 'stable',
      name: t('models:presets.stable.name', 'Demanda Estable'),
      description: t('models:presets.stable.description', 'Para ingredientes básicos con demanda constante. Mínima estacionalidad.'),
      icon: Box,
      settings: {
        seasonality_mode: 'additive',
        daily_seasonality: false,
        weekly_seasonality: true,
        yearly_seasonality: false,
      }
    },
    {
      id: 'custom',
      name: t('models:presets.custom.name', 'Personalizado'),
      description: t('models:presets.custom.description', 'Configuración avanzada con control total sobre los parámetros.'),
      icon: Settings,
      settings: advancedSettings
    }
  ], [t, advancedSettings]);

  const handleRetrain = async () => {
    let settings: SingleProductTrainingRequest;

    switch (mode) {
      case 'quick':
        // Use existing model's hyperparameters if available
        settings = currentModel?.hyperparameters || {
          seasonality_mode: 'additive',
          daily_seasonality: true,
          weekly_seasonality: true,
          yearly_seasonality: false,
        };
        break;
      case 'preset':
        const preset = presets.find(p => p.id === selectedPreset);
        settings = preset?.settings || presets[0].settings;
        break;
      case 'advanced':
        settings = advancedSettings;
        break;
      default:
        settings = advancedSettings;
    }

    await onRetrain(settings);
  };

  // Build sections based on current mode - memoized to prevent recreation
  const sections = React.useMemo((): EditViewModalSection[] => {
    const result: EditViewModalSection[] = [];

    if (mode === 'quick') {
      result.push({
        title: t('models:retrain.quick.title', 'Reentrenamiento Rápido'),
        icon: Zap,
        fields: [
          {
            label: t('models:retrain.quick.ingredient', 'Ingrediente'),
            value: ingredient.name,
            type: 'text',
            highlight: true
          },
          {
            label: t('models:retrain.quick.current_accuracy', 'Precisión Actual'),
            value: currentModel?.training_metrics?.mape
              ? `${(100 - currentModel.training_metrics.mape).toFixed(1)}%`
              : t('common:not_available', 'N/A'),
            type: 'text'
          },
          {
            label: t('models:retrain.quick.last_training', 'Último Entrenamiento'),
            value: currentModel?.created_at || t('common:not_available', 'N/A'),
            type: 'date'
          },
          {
            label: t('models:retrain.quick.description', 'Descripción'),
            value: t('models:retrain.quick.description_text', 'El reentrenamiento rápido utiliza la misma configuración del modelo actual pero con los datos más recientes. Esto mantiene la precisión del modelo actualizada sin cambiar su comportamiento.'),
            type: 'text',
            span: 2
          }
        ]
      });
    }

    if (mode === 'preset') {
      // Show preset selection
      result.push({
        title: t('models:retrain.preset.title', 'Seleccionar Configuración'),
        icon: Sparkles,
        fields: [
          {
            label: t('models:retrain.preset.ingredient', 'Ingrediente'),
            value: ingredient.name,
            type: 'text',
            highlight: true
          },
          {
            label: t('models:retrain.preset.select', 'Tipo de Producto'),
            value: selectedPreset,
            type: 'select',
            editable: true,
            options: presets.map(p => ({ label: p.name, value: p.id })),
            span: 2
          }
        ]
      });

      // Show description of selected preset
      const currentPreset = presets.find(p => p.id === selectedPreset);
      if (currentPreset) {
        result.push({
          title: currentPreset.name,
          icon: currentPreset.icon,
          fields: [
            {
              label: t('models:retrain.preset.description', 'Descripción'),
              value: currentPreset.description,
              type: 'text',
              span: 2
            },
            {
              label: t('models:retrain.preset.seasonality_mode', 'Modo de Estacionalidad'),
              value: currentPreset.settings.seasonality_mode === 'additive'
                ? t('models:seasonality.additive', 'Aditivo')
                : t('models:seasonality.multiplicative', 'Multiplicativo'),
              type: 'text'
            },
            {
              label: t('models:retrain.preset.daily', 'Estacionalidad Diaria'),
              value: currentPreset.settings.daily_seasonality
                ? t('common:yes', 'Sí')
                : t('common:no', 'No'),
              type: 'text'
            },
            {
              label: t('models:retrain.preset.weekly', 'Estacionalidad Semanal'),
              value: currentPreset.settings.weekly_seasonality
                ? t('common:yes', 'Sí')
                : t('common:no', 'No'),
              type: 'text'
            },
            {
              label: t('models:retrain.preset.yearly', 'Estacionalidad Anual'),
              value: currentPreset.settings.yearly_seasonality
                ? t('common:yes', 'Sí')
                : t('common:no', 'No'),
              type: 'text'
            }
          ]
        });
      }
    }

    if (mode === 'advanced') {
      result.push({
        title: t('models:retrain.advanced.title', 'Configuración Avanzada'),
        icon: Settings,
        fields: [
          {
            label: t('models:retrain.advanced.ingredient', 'Ingrediente'),
            value: ingredient.name,
            type: 'text',
            highlight: true,
            span: 2
          },
          {
            label: t('models:retrain.advanced.start_date', 'Fecha de Inicio'),
            value: advancedSettings.start_date || '',
            type: 'date',
            editable: true,
            helpText: t('models:retrain.advanced.start_date_help', 'Dejar vacío para usar todos los datos disponibles')
          },
          {
            label: t('models:retrain.advanced.end_date', 'Fecha de Fin'),
            value: advancedSettings.end_date || '',
            type: 'date',
            editable: true,
            helpText: t('models:retrain.advanced.end_date_help', 'Dejar vacío para usar hasta la fecha actual')
          },
          {
            label: t('models:retrain.advanced.seasonality_mode', 'Modo de Estacionalidad'),
            value: advancedSettings.seasonality_mode || 'additive',
            type: 'select',
            editable: true,
            options: [
              { label: t('models:seasonality.additive', 'Aditivo'), value: 'additive' },
              { label: t('models:seasonality.multiplicative', 'Multiplicativo'), value: 'multiplicative' }
            ],
            helpText: t('models:retrain.advanced.seasonality_mode_help', 'Aditivo: cambios constantes. Multiplicativo: cambios proporcionales.')
          }
        ]
      });

      // Seasonality options
      result.push({
        title: t('models:retrain.advanced.seasonality_patterns', 'Patrones Estacionales'),
        icon: Calendar,
        fields: [
          {
            label: t('models:retrain.advanced.daily_seasonality', 'Estacionalidad Diaria'),
            value: advancedSettings.daily_seasonality ? t('common:enabled', 'Activado') : t('common:disabled', 'Desactivado'),
            type: 'text',
            helpText: t('models:retrain.advanced.daily_seasonality_help', 'Patrones que se repiten cada día')
          },
          {
            label: t('models:retrain.advanced.weekly_seasonality', 'Estacionalidad Semanal'),
            value: advancedSettings.weekly_seasonality ? t('common:enabled', 'Activado') : t('common:disabled', 'Desactivado'),
            type: 'text',
            helpText: t('models:retrain.advanced.weekly_seasonality_help', 'Patrones que se repiten cada semana')
          },
          {
            label: t('models:retrain.advanced.yearly_seasonality', 'Estacionalidad Anual'),
            value: advancedSettings.yearly_seasonality ? t('common:enabled', 'Activado') : t('common:disabled', 'Desactivado'),
            type: 'text',
            helpText: t('models:retrain.advanced.yearly_seasonality_help', 'Patrones que se repiten cada año (festividades, temporadas)')
          }
        ]
      });
    }

    return result;
  }, [mode, t, ingredient, currentModel, presets, selectedPreset, advancedSettings]);

  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number) => {
    const field = sections[sectionIndex]?.fields[fieldIndex];

    if (!field) return;

    // Handle preset selection
    if (mode === 'preset' && field.label === t('models:retrain.preset.select', 'Tipo de Producto')) {
      setSelectedPreset(value as string);
      return;
    }

    // Handle advanced settings
    if (mode === 'advanced') {
      const label = field.label;

      if (label === t('models:retrain.advanced.start_date', 'Fecha de Inicio')) {
        setAdvancedSettings(prev => ({ ...prev, start_date: value as string || null }));
      } else if (label === t('models:retrain.advanced.end_date', 'Fecha de Fin')) {
        setAdvancedSettings(prev => ({ ...prev, end_date: value as string || null }));
      } else if (label === t('models:retrain.advanced.seasonality_mode', 'Modo de Estacionalidad')) {
        setAdvancedSettings(prev => ({ ...prev, seasonality_mode: value as string }));
      }
    }
  };

  // Header navigation actions (tabs)
  const headerActions = React.useMemo(() => [
    {
      label: t('models:retrain.modes.quick', 'Rápido'),
      icon: Zap,
      onClick: () => setMode('quick'),
      variant: 'outline',
      disabled: mode === 'quick'
    },
    {
      label: t('models:retrain.modes.preset', 'Preconfigurado'),
      icon: Sparkles,
      onClick: () => setMode('preset'),
      variant: 'outline',
      disabled: mode === 'preset'
    },
    {
      label: t('models:retrain.modes.advanced', 'Avanzado'),
      icon: Settings,
      onClick: () => setMode('advanced'),
      variant: 'outline',
      disabled: mode === 'advanced'
    }
  ], [t, mode]);

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={() => {
        setMode('quick');
        onClose();
      }}
      mode="edit" // Keep in edit mode so it shows Cancel/Save
      title={t('models:retrain.title', 'Reentrenar Modelo')}
      subtitle={ingredient.name}
      statusIndicator={{
        color: '#F59E0B',
        text: t('models:status.retraining', 'Reentrenamiento'),
        icon: RotateCcw,
        isCritical: false,
        isHighlight: true
      }}
      size="lg"
      sections={sections}
      actions={headerActions}
      actionsPosition="header"
      showDefaultActions={true} // Enable default actions (Cancel/Save)
      saveLabel={t('models:retrain.start', 'Iniciar Reentrenamiento')} // Custom save button label for retraining
      onSave={handleRetrain}
      onFieldChange={handleFieldChange}
      loading={isLoading}
    />
  );
};

export default RetrainModelModal;
