import React, { useState, useEffect } from 'react';
import { Plus, Settings, ClipboardCheck, Target, Cog } from 'lucide-react';
import { AddModal } from '../../ui/AddModal/AddModal';
import { Select } from '../../ui/Select';
import {
  QualityCheckType,
  ProcessStage,
  type QualityCheckTemplateCreate
} from '../../../api/types/qualityTemplates';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useAuthUser } from '../../../stores/auth.store';
import { useQuery } from '@tanstack/react-query';
import { recipesService } from '../../../api/services/recipes';
import type { RecipeResponse } from '../../../api/types/recipes';
import { statusColors } from '../../../styles/colors';
import { useTranslation } from 'react-i18next';

interface CreateQualityTemplateModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreateTemplate: (templateData: QualityCheckTemplateCreate, recipeAssociations?: RecipeAssociation[]) => Promise<void>;
  isLoading?: boolean;
  initialRecipe?: RecipeResponse; // Pre-select recipe if coming from recipe page
}

interface RecipeAssociation {
  recipeId: string;
  recipeName: string;
  stages: ProcessStage[];
}

const QUALITY_CHECK_TYPE_OPTIONS = [
  { value: QualityCheckType.VISUAL, label: 'Visual - Inspección visual' },
  { value: QualityCheckType.MEASUREMENT, label: 'Medición - Medidas precisas' },
  { value: QualityCheckType.TEMPERATURE, label: 'Temperatura - Control térmico' },
  { value: QualityCheckType.WEIGHT, label: 'Peso - Control de peso' },
  { value: QualityCheckType.BOOLEAN, label: 'Sí/No - Verificación binaria' },
  { value: QualityCheckType.TIMING, label: 'Tiempo - Control temporal' },
  { value: QualityCheckType.CHECKLIST, label: 'Checklist - Lista de verificación' }
];

const PROCESS_STAGE_OPTIONS = [
  { value: ProcessStage.MIXING, label: 'Mezclado' },
  { value: ProcessStage.PROOFING, label: 'Fermentación' },
  { value: ProcessStage.SHAPING, label: 'Formado' },
  { value: ProcessStage.BAKING, label: 'Horneado' },
  { value: ProcessStage.COOLING, label: 'Enfriado' },
  { value: ProcessStage.PACKAGING, label: 'Empaquetado' },
  { value: ProcessStage.FINISHING, label: 'Acabado' }
];

const CATEGORY_OPTIONS_KEYS = [
  { value: 'appearance', key: 'appearance' },
  { value: 'structure', key: 'structure' },
  { value: 'texture', key: 'texture' },
  { value: 'flavor', key: 'flavor' },
  { value: 'safety', key: 'safety' },
  { value: 'packaging', key: 'packaging' },
  { value: 'temperature', key: 'temperature' },
  { value: 'weight', key: 'weight' },
  { value: 'dimensions', key: 'dimensions' },
  { value: 'weight_check', key: 'weight_check' },
  { value: 'temperature_check', key: 'temperature_check' },
  { value: 'moisture_check', key: 'moisture_check' },
  { value: 'volume_check', key: 'volume_check' },
  { value: 'time_check', key: 'time_check' },
  { value: 'chemical', key: 'chemical' },
  { value: 'hygiene', key: 'hygiene' }
];

export const CreateQualityTemplateModal: React.FC<CreateQualityTemplateModalProps> = ({
  isOpen,
  onClose,
  onCreateTemplate,
  isLoading: externalLoading = false,
  initialRecipe
}) => {
  const { t } = useTranslation(['production', 'common']);
  const currentTenant = useCurrentTenant();
  const user = useAuthUser();
  const [loading, setLoading] = useState(false);
  const [selectedStages, setSelectedStages] = useState<ProcessStage[]>([]);
  const [selectedCheckType, setSelectedCheckType] = useState<QualityCheckType | null>(null);

  // Helper function to get translated category label
  const getCategoryLabel = (category: string | null | undefined): string => {
    if (!category) return t('production:quality.categories.no_category', 'Sin categoría');
    const translationKey = `quality.categories.${category}`;
    const translated = t(`production:${translationKey}`);
    return translated === `production:${translationKey}` ? category : translated;
  };

  // Build category options with translations
  const getCategoryOptions = () => {
    return CATEGORY_OPTIONS_KEYS.map(option => ({
      value: option.value,
      label: getCategoryLabel(option.key)
    }));
  };

  // Fetch available recipes for association
  const { data: recipes, isLoading: recipesLoading } = useQuery({
    queryKey: ['recipes', currentTenant?.id],
    queryFn: () => recipesService.searchRecipes(currentTenant?.id || '', { limit: 1000 }),
    enabled: isOpen && !!currentTenant?.id
  });

  const recipeOptions = recipes?.map(recipe => ({
    value: recipe.id,
    label: `${recipe.name}${recipe.category ? ` (${recipe.category})` : ''}`
  })) || [];

  const handleSave = async (formData: Record<string, any>) => {
    setLoading(true);

    try {
      // Type-specific validation
      if (formData.check_type === QualityCheckType.VISUAL) {
        const hasAnyScoring = formData.scoring_excellent_min || formData.scoring_excellent_max ||
                              formData.scoring_good_min || formData.scoring_good_max ||
                              formData.scoring_acceptable_min || formData.scoring_acceptable_max;
        if (!hasAnyScoring) {
          throw new Error('Los criterios de puntuación son requeridos para controles visuales');
        }
      }

      if ([QualityCheckType.MEASUREMENT, QualityCheckType.TEMPERATURE, QualityCheckType.WEIGHT].includes(formData.check_type)) {
        if (!formData.unit?.trim()) {
          throw new Error('La unidad es requerida para controles de medición, temperatura y peso');
        }
      }

      // Process applicable stages - convert string back to array
      const applicableStages = formData.applicable_stages
        ? (typeof formData.applicable_stages === 'string'
            ? formData.applicable_stages.split(',').filter(Boolean)
            : formData.applicable_stages)
        : [];

      // Build scoring criteria for visual checks
      let scoringCriteria: Record<string, any> | undefined;
      if (formData.check_type === QualityCheckType.VISUAL) {
        scoringCriteria = {
          excellent: {
            min: formData.scoring_excellent_min ? Number(formData.scoring_excellent_min) : undefined,
            max: formData.scoring_excellent_max ? Number(formData.scoring_excellent_max) : undefined
          },
          good: {
            min: formData.scoring_good_min ? Number(formData.scoring_good_min) : undefined,
            max: formData.scoring_good_max ? Number(formData.scoring_good_max) : undefined
          },
          acceptable: {
            min: formData.scoring_acceptable_min ? Number(formData.scoring_acceptable_min) : undefined,
            max: formData.scoring_acceptable_max ? Number(formData.scoring_acceptable_max) : undefined
          },
          fail: {
            below: formData.scoring_fail_below ? Number(formData.scoring_fail_below) : undefined,
            above: formData.scoring_fail_above ? Number(formData.scoring_fail_above) : undefined
          }
        };
      }

      const templateData: QualityCheckTemplateCreate = {
        name: formData.name,
        template_code: formData.template_code || '',
        check_type: formData.check_type as QualityCheckType,
        category: formData.category || '',
        description: formData.description || '',
        instructions: formData.instructions || '',
        is_active: formData.is_active !== false,
        is_required: formData.is_required || false,
        is_critical: formData.is_critical || false,
        weight: Number(formData.weight) || 1.0,
        applicable_stages: applicableStages.length > 0 ? applicableStages as ProcessStage[] : undefined,
        created_by: user?.id || '',
        // Measurement fields
        min_value: formData.min_value ? Number(formData.min_value) : undefined,
        max_value: formData.max_value ? Number(formData.max_value) : undefined,
        target_value: formData.target_value ? Number(formData.target_value) : undefined,
        unit: formData.unit && formData.unit.trim() ? formData.unit.trim() : undefined,
        tolerance_percentage: formData.tolerance_percentage ? Number(formData.tolerance_percentage) : undefined,
        // Scoring criteria (for visual checks)
        scoring_criteria: scoringCriteria
      };

      // Handle recipe associations if provided
      let recipeAssociations: RecipeAssociation[] | undefined;
      if (formData.associated_recipe_id) {
        const selectedRecipe = recipes?.find(r => r.id === formData.associated_recipe_id);
        if (selectedRecipe && applicableStages.length > 0) {
          recipeAssociations = [{
            recipeId: selectedRecipe.id,
            recipeName: selectedRecipe.name,
            stages: applicableStages as ProcessStage[]
          }];
        }
      }

      await onCreateTemplate(templateData, recipeAssociations);

      // Reset state
      setSelectedStages([]);
    } catch (error) {
      console.error('Error creating template:', error);
      throw error; // Let AddModal handle error display
    } finally {
      setLoading(false);
    }
  };

  const statusConfig = {
    color: statusColors.inProgress.primary,
    text: 'Nueva Plantilla',
    icon: Plus,
    isCritical: false,
    isHighlight: true
  };

  // Handler for field changes to track check_type selection
  const handleFieldChange = (fieldName: string, value: any) => {
    if (fieldName === 'check_type') {
      setSelectedCheckType(value as QualityCheckType);
    }
  };

  // Function to build sections dynamically based on selected check type
  const getSections = () => {
    const basicInfoSection = {
      title: 'Información Básica',
      icon: ClipboardCheck,
      fields: [
        {
          label: 'Nombre',
          name: 'name',
          type: 'text' as const,
          required: true,
          placeholder: 'Ej: Control Visual de Pan',
          validation: (value: string | number) => {
            const str = String(value).trim();
            return str.length < 3 ? 'El nombre debe tener al menos 3 caracteres' : null;
          }
        },
        {
          label: 'Código de Plantilla',
          name: 'template_code',
          type: 'text' as const,
          placeholder: 'Ej: CV_PAN_01'
        },
        {
          label: 'Tipo de Control',
          name: 'check_type',
          type: 'select' as const,
          required: true,
          placeholder: 'Selecciona un tipo de control...',
          options: QUALITY_CHECK_TYPE_OPTIONS,
          helpText: 'Los campos de configuración cambiarán según el tipo seleccionado'
        },
        {
          label: 'Categoría',
          name: 'category',
          type: 'select' as const,
          options: getCategoryOptions(),
          placeholder: 'Seleccionar categoría'
        },
        {
          label: 'Descripción',
          name: 'description',
          type: 'textarea' as const,
          placeholder: 'Describe qué evalúa esta plantilla de calidad',
          span: 2 as const
        },
        {
          label: 'Instrucciones para el Personal',
          name: 'instructions',
          type: 'textarea' as const,
          placeholder: 'Instrucciones detalladas para realizar este control de calidad',
          span: 2 as const,
          helpText: 'Pasos específicos que debe seguir el operario'
        }
      ]
    };

    const measurementSection = {
      title: 'Configuración de Medición',
      icon: Target,
      fields: [
        {
          label: 'Valor Mínimo',
          name: 'min_value',
          type: 'number' as const,
          placeholder: '0',
          helpText: 'Valor mínimo aceptable para la medición'
        },
        {
          label: 'Valor Máximo',
          name: 'max_value',
          type: 'number' as const,
          placeholder: '100',
          helpText: 'Valor máximo aceptable para la medición'
        },
        {
          label: 'Valor Objetivo',
          name: 'target_value',
          type: 'number' as const,
          placeholder: '50',
          helpText: 'Valor ideal que se busca alcanzar'
        },
        {
          label: 'Unidad *',
          name: 'unit',
          type: 'text' as const,
          required: true,
          placeholder: '°C / g / cm',
          helpText: 'REQUERIDO para este tipo de control (ej: °C, g, cm)'
        },
        {
          label: 'Tolerancia (%)',
          name: 'tolerance_percentage',
          type: 'number' as const,
          placeholder: '5',
          helpText: 'Porcentaje de tolerancia permitido'
        }
      ]
    };

    const scoringSection = {
      title: 'Criterios de Puntuación (Controles Visuales)',
      icon: Target,
      fields: [
        {
          label: 'Excelente - Mínimo',
          name: 'scoring_excellent_min',
          type: 'number' as const,
          placeholder: '9.0',
          helpText: 'Puntuación mínima para nivel excelente'
        },
        {
          label: 'Excelente - Máximo',
          name: 'scoring_excellent_max',
          type: 'number' as const,
          placeholder: '10.0',
          helpText: 'Puntuación máxima para nivel excelente'
        },
        {
          label: 'Bueno - Mínimo',
          name: 'scoring_good_min',
          type: 'number' as const,
          placeholder: '7.0',
          helpText: 'Puntuación mínima para nivel bueno'
        },
        {
          label: 'Bueno - Máximo',
          name: 'scoring_good_max',
          type: 'number' as const,
          placeholder: '8.9',
          helpText: 'Puntuación máxima para nivel bueno'
        },
        {
          label: 'Aceptable - Mínimo',
          name: 'scoring_acceptable_min',
          type: 'number' as const,
          placeholder: '5.0',
          helpText: 'Puntuación mínima para nivel aceptable'
        },
        {
          label: 'Aceptable - Máximo',
          name: 'scoring_acceptable_max',
          type: 'number' as const,
          placeholder: '6.9',
          helpText: 'Puntuación máxima para nivel aceptable'
        },
        {
          label: 'Fallo - Por Debajo',
          name: 'scoring_fail_below',
          type: 'number' as const,
          placeholder: '5.0',
          helpText: 'Valor por debajo del cual se considera fallo'
        },
        {
          label: 'Fallo - Por Encima',
          name: 'scoring_fail_above',
          type: 'number' as const,
          placeholder: '10.0',
          helpText: 'Valor por encima del cual se considera fallo (opcional)'
        }
      ]
    };

    const stagesSection = {
      title: 'Etapas del Proceso',
      icon: Settings,
      fields: [
        {
          label: 'Etapas Aplicables',
          name: 'applicable_stages',
          type: 'component' as const,
          component: Select,
          componentProps: {
            options: PROCESS_STAGE_OPTIONS,
            multiple: true,
            placeholder: 'Seleccionar etapas del proceso',
            searchable: true
          },
          helpText: 'Selecciona las etapas donde se aplicará este control de calidad',
          span: 2 as const
        }
      ]
    };

    const recipesSection = {
      title: 'Asociación con Recetas',
      icon: Plus,
      fields: [
        {
          label: 'Asociar a Receta (Opcional)',
          name: 'associated_recipe_id',
          type: 'select' as const,
          options: recipeOptions,
          placeholder: 'Seleccionar receta para asociar automáticamente',
          helpText: 'Si seleccionas una receta, esta plantilla se aplicará automáticamente a sus lotes de producción',
          span: 2 as const
        }
      ]
    };

    const advancedSection = {
      title: 'Configuración Avanzada',
      icon: Cog,
      fields: [
        {
          label: 'Peso en Puntuación General',
          name: 'weight',
          type: 'number' as const,
          defaultValue: 1.0,
          placeholder: '1.0',
          validation: (value: string | number) => {
            const num = Number(value);
            return num < 0 || num > 10 ? 'El peso debe estar entre 0 y 10' : null;
          },
          helpText: 'Mayor peso = mayor importancia en la puntuación final (0-10)'
        },
        {
          label: 'Plantilla Activa',
          name: 'is_active',
          type: 'select' as const,
          options: [
            { value: 'true', label: 'Sí' },
            { value: 'false', label: 'No' }
          ],
          defaultValue: 'true'
        },
        {
          label: 'Control Requerido',
          name: 'is_required',
          type: 'select' as const,
          options: [
            { value: 'false', label: 'Opcional' },
            { value: 'true', label: 'Requerido' }
          ],
          defaultValue: 'false',
          helpText: 'Si es requerido, debe completarse obligatoriamente'
        },
        {
          label: 'Control Crítico',
          name: 'is_critical',
          type: 'select' as const,
          options: [
            { value: 'false', label: 'Normal' },
            { value: 'true', label: 'Crítico' }
          ],
          defaultValue: 'false',
          helpText: 'Si es crítico, bloquea la producción si falla'
        }
      ]
    };

    // Build sections array based on selected check type
    const sections = [basicInfoSection];

    // Add type-specific configuration sections
    if (selectedCheckType === QualityCheckType.VISUAL) {
      sections.push(scoringSection);
    } else if ([QualityCheckType.MEASUREMENT, QualityCheckType.TEMPERATURE, QualityCheckType.WEIGHT].includes(selectedCheckType as QualityCheckType)) {
      sections.push(measurementSection);
    }
    // For BOOLEAN, TIMING, CHECKLIST - no special configuration sections yet

    // Always add these sections
    sections.push(stagesSection);
    sections.push(recipesSection);
    sections.push(advancedSection);

    return sections;
  };

  const sections = getSections();

  return (
    <>
      <AddModal
        isOpen={isOpen}
        onClose={onClose}
        title="Nueva Plantilla de Control de Calidad"
        subtitle="Crear una plantilla para controles de calidad estandarizados"
        statusIndicator={statusConfig}
        sections={sections}
        size="xl"
        loading={loading || externalLoading}
        onSave={handleSave}
        onFieldChange={handleFieldChange}
      />
    </>
  );
};

export default CreateQualityTemplateModal;
