import React, { useState } from 'react';
import { Package, AlertTriangle, CheckCircle, Clock, Euro, Edit, Info, Thermometer, Calendar, Tag, Save, X, TrendingUp } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { EditViewModal } from '../../ui/EditViewModal/EditViewModal';
import { IngredientResponse, IngredientCategory, ProductCategory, ProductType, UnitOfMeasure } from '../../../api/types/inventory';
import { formatters } from '../../ui/Stats/StatsPresets';
import { statusColors } from '../../../styles/colors';

interface ShowInfoModalProps {
  isOpen: boolean;
  onClose: () => void;
  ingredient: IngredientResponse;
  onSave?: (updatedData: Partial<IngredientResponse>) => Promise<void>;
  // Wait-for-refetch support
  waitForRefetch?: boolean;
  isRefetching?: boolean;
  onSaveComplete?: () => Promise<void>;
}

/**
 * ShowInfoModal - Complete item details modal
 * Shows ALL item information excluding stock, lots, and movements data
 * Includes edit functionality for item properties
 */
export const ShowInfoModal: React.FC<ShowInfoModalProps> = ({
  isOpen,
  onClose,
  ingredient,
  onSave,
  waitForRefetch,
  isRefetching,
  onSaveComplete
}) => {
  const { t } = useTranslation(['inventory', 'common']);
  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState<Partial<IngredientResponse>>({});

  const handleEdit = () => {
    setIsEditing(true);
    setEditData(ingredient);
  };

  const handleCancel = () => {
    setIsEditing(false);
    setEditData({});
  };

  const handleSave = async () => {
    if (onSave) {
      // CRITICAL: Capture editData IMMEDIATELY before any async operations
      // This prevents race conditions where editData might be cleared by React state updates
      const dataToSave = { ...editData };

      // Validate we have data to save
      if (Object.keys(dataToSave).length === 0) {
        console.error('ShowInfoModal: No edit data to save');
        return;
      }

      console.log('ShowInfoModal: Saving data:', dataToSave);
      await onSave(dataToSave);

      // Note: Don't clear edit state here - let EditViewModal handle mode switching
      // after refetch completes if waitForRefetch is enabled
      if (!waitForRefetch) {
        setIsEditing(false);
        setEditData({});
      }
    }
  };

  // Reset edit state when mode changes to view (after refetch completes)
  React.useEffect(() => {
    if (!isEditing) {
      setEditData({});
    }
  }, [isEditing]);

  // Status configuration based on item status (not stock)
  const statusConfig = {
    color: ingredient.is_active ? statusColors.normal.primary : statusColors.cancelled.primary,
    text: ingredient.is_active ? t('common:status.active') : t('common:status.inactive'),
    icon: ingredient.is_active ? CheckCircle : AlertTriangle,
    isCritical: !ingredient.is_active
  };

  const currentData = isEditing ? editData : ingredient;

  // Helper function to translate enum values
  const translateEnum = (enumType: string, value: string | undefined) => {
    if (!value) return '';
    return t(`enums.${enumType}.${value}`, { defaultValue: value });
  };

  // Helper to get translated category (falls back to common if not in inventory)
  const getTranslatedCategory = (category: string | undefined) => {
    if (!category) return '';
    // Try inventory namespace first, then common namespace
    const translated = t(`enums.ingredient_category.${category}`, { defaultValue: '' });
    return translated || t(`common:categories.${category}`, { defaultValue: category });
  };

  // Get category options (combining ingredient and product categories)
  const getCategoryOptions = () => {
    const ingredientCategories = Object.values(IngredientCategory).map(value => ({
      value,
      label: t(`enums.ingredient_category.${value}`)
    }));

    const productCategories = Object.values(ProductCategory).map(value => ({
      value,
      label: t(`enums.product_category.${value}`)
    }));

    return [...ingredientCategories, ...productCategories].sort((a, b) => a.label.localeCompare(b.label));
  };

  // Get product type options
  const getProductTypeOptions = () => {
    return Object.values(ProductType).map(value => ({
      value,
      label: t(`enums.product_type.${value}`)
    }));
  };

  // Get unit of measure options
  const getUnitOfMeasureOptions = () => {
    return Object.values(UnitOfMeasure).map(value => ({
      value,
      label: t(`enums.unit_of_measure.${value}`)
    }));
  };

  const sections = [
    {
      title: t('fields.basic_info', { defaultValue: 'Información Básica' }),
      icon: Info,
      fields: [
        {
          label: t('common:fields.name'),
          value: currentData.name || '',
          highlight: true,
          span: 2 as const,
          editable: true,
          required: true
        },
        {
          label: t('common:fields.description'),
          value: currentData.description || '',
          span: 2 as const,
          editable: true,
          placeholder: t('common:fields.description')
        },
        {
          label: t('labels.ingredient_category'),
          value: isEditing ? currentData.category || '' : getTranslatedCategory(currentData.category),
          span: 1 as const,
          editable: true,
          required: true,
          type: 'select' as const,
          options: getCategoryOptions(),
          placeholder: t('labels.ingredient_category')
        },
        {
          label: t('fields.subcategory', { defaultValue: 'Subcategoría' }),
          value: currentData.subcategory || '',
          span: 1 as const,
          editable: true,
          placeholder: t('fields.subcategory', { defaultValue: 'Subcategoría' })
        },
        {
          label: t('fields.brand', { defaultValue: 'Marca' }),
          value: currentData.brand || '',
          span: 1 as const,
          editable: true,
          placeholder: t('fields.brand', { defaultValue: 'Marca del producto' })
        },
        {
          label: t('labels.product_type'),
          value: isEditing ? currentData.product_type || '' : translateEnum('product_type', currentData.product_type),
          span: 1 as const,
          editable: true,
          type: 'select' as const,
          options: getProductTypeOptions(),
          placeholder: t('labels.product_type')
        }
      ]
    },
    {
      title: t('fields.specifications', { defaultValue: 'Especificaciones' }),
      icon: Package,
      fields: [
        {
          label: t('labels.unit_of_measure'),
          value: isEditing ? currentData.unit_of_measure || '' : translateEnum('unit_of_measure', currentData.unit_of_measure),
          span: 1 as const,
          editable: true,
          required: true,
          type: 'select' as const,
          options: getUnitOfMeasureOptions(),
          placeholder: t('labels.unit_of_measure')
        },
        {
          label: t('fields.package_size', { defaultValue: 'Tamaño del Paquete' }),
          value: currentData.package_size || '',
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: t('fields.package_size', { defaultValue: 'Tamaño del paquete' })
        },
        {
          label: t('fields.is_perishable', { defaultValue: 'Es Perecedero' }),
          value: isEditing ? String(currentData.is_perishable) : (currentData.is_perishable ? t('common:modals.actions.yes') : t('common:modals.actions.no')),
          span: 1 as const,
          editable: true,
          type: 'select' as const,
          options: [
            { label: t('common:modals.actions.yes'), value: 'true' },
            { label: t('common:modals.actions.no'), value: 'false' }
          ]
        },
        {
          label: t('fields.is_seasonal', { defaultValue: 'Es de Temporada' }),
          value: isEditing ? String(currentData.is_seasonal) : (currentData.is_seasonal ? t('common:modals.actions.yes') : t('common:modals.actions.no')),
          span: 1 as const,
          editable: true,
          type: 'select' as const,
          options: [
            { label: t('common:modals.actions.yes'), value: 'true' },
            { label: t('common:modals.actions.no'), value: 'false' }
          ]
        }
      ]
    },
    {
      title: t('fields.costs_and_pricing', { defaultValue: 'Costos y Precios' }),
      icon: Euro,
      fields: [
        {
          label: t('fields.average_cost', { defaultValue: 'Costo Promedio' }),
          value: Number(currentData.average_cost) || 0,
          type: 'currency' as const,
          span: 1 as const,
          editable: true,
          placeholder: '0.00'
        },
        {
          label: t('fields.last_purchase_price', { defaultValue: 'Último Precio de Compra' }),
          value: Number(currentData.last_purchase_price) || 0,
          type: 'currency' as const,
          span: 1 as const,
          editable: true,
          placeholder: '0.00'
        },
        {
          label: t('fields.standard_cost', { defaultValue: 'Costo Estándar' }),
          value: Number(currentData.standard_cost) || 0,
          type: 'currency' as const,
          span: 2 as const,
          editable: true,
          placeholder: '0.00'
        }
      ]
    },
    {
      title: t('fields.inventory_parameters', { defaultValue: 'Parámetros de Inventario' }),
      icon: TrendingUp,
      fields: [
        {
          label: t('fields.low_stock_threshold', { defaultValue: 'Umbral Stock Bajo' }),
          value: currentData.low_stock_threshold || 0,
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: t('fields.low_stock_threshold', { defaultValue: 'Cantidad mínima antes de alerta' })
        },
        {
          label: t('fields.reorder_point', { defaultValue: 'Punto de Reorden' }),
          value: currentData.reorder_point || 0,
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: t('fields.reorder_point', { defaultValue: 'Punto para reordenar' })
        },
        {
          label: t('fields.reorder_quantity', { defaultValue: 'Cantidad de Reorden' }),
          value: currentData.reorder_quantity || 0,
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: t('fields.reorder_quantity', { defaultValue: 'Cantidad a reordenar' })
        },
        {
          label: t('fields.max_stock_level', { defaultValue: 'Stock Máximo' }),
          value: currentData.max_stock_level || '',
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: t('fields.max_stock_level', { defaultValue: 'Cantidad máxima permitida' })
        }
      ]
    }
  ];

  // Note: We'll let EditViewModal handle default actions (Edit/Save/Cancel)
  // by setting showDefaultActions=true instead of providing custom actions

  // Handle field changes
  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number) => {
    if (!isEditing) return;

    // Map field indices to ingredient properties
    const fieldMappings = [
      // Section 0: Información Básica
      ['name', 'description', 'category', 'subcategory', 'brand', 'product_type'],
      // Section 1: Especificaciones
      ['unit_of_measure', 'package_size', 'is_perishable', 'is_seasonal'],
      // Section 2: Costos y Precios
      ['average_cost', 'last_purchase_price', 'standard_cost'],
      // Section 3: Parámetros de Inventario
      ['low_stock_threshold', 'reorder_point', 'reorder_quantity', 'max_stock_level']
    ];

    const fieldName = fieldMappings[sectionIndex]?.[fieldIndex];
    if (!fieldName) return;

    let processedValue: string | number | boolean = value;

    // Handle boolean fields
    if (fieldName === 'is_perishable' || fieldName === 'is_seasonal') {
      processedValue = value === 'true';
    }
    // Handle numeric fields
    else if (fieldName === 'package_size' || fieldName.includes('cost') || fieldName.includes('price') ||
        fieldName.includes('threshold') || fieldName.includes('point') || fieldName.includes('quantity') ||
        fieldName.includes('level')) {
      processedValue = Number(value) || 0;
    }

    setEditData(prev => ({
      ...prev,
      [fieldName]: processedValue
    }));
  };

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={onClose}
      mode={isEditing ? "edit" : "view"}
      onModeChange={(mode) => {
        const isEditMode = mode === 'edit';
        setIsEditing(isEditMode);
        if (isEditMode) {
          setEditData(ingredient);  // Populate editData when entering edit mode
        }
      }}
      title={ingredient.name}
      subtitle={getTranslatedCategory(ingredient.category)}
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      showDefaultActions={true}
      onFieldChange={handleFieldChange}
      onSave={handleSave}
      onCancel={handleCancel}
      waitForRefetch={waitForRefetch}
      isRefetching={isRefetching}
      onSaveComplete={onSaveComplete}
    />
  );
};

export default ShowInfoModal;