import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus, Package, Calculator, Settings } from 'lucide-react';
import { AddModal } from '../../ui/AddModal/AddModal';
import { IngredientCreate, UnitOfMeasure, IngredientCategory, ProductCategory } from '../../../api/types/inventory';
import { statusColors } from '../../../styles/colors';

interface CreateIngredientModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreateIngredient?: (ingredientData: IngredientCreate) => Promise<void>;
}

/**
 * CreateIngredientModal - Modal for creating a new inventory ingredient
 * Comprehensive form for adding new items to inventory
 */
export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
  isOpen,
  onClose,
  onCreateIngredient
}) => {
  const { t } = useTranslation(['inventory', 'common']);
  const [loading, setLoading] = useState(false);

  // Get enum options using direct i18n implementation
  const ingredientCategoryOptions = Object.values(IngredientCategory).map(value => ({
    value,
    label: t(`inventory:enums.ingredient_category.${value}`)
  })).sort((a, b) => a.label.localeCompare(b.label));

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

  const categoryOptions = [
    ...ingredientCategoryOptions,
    ...productCategoryOptions
  ];

  const unitOptions = Object.values(UnitOfMeasure).map(value => ({
    value,
    label: t(`inventory:enums.unit_of_measure.${value}`)
  }));

  const handleSave = async (formData: Record<string, any>) => {
    // Transform form data to IngredientCreate format
    const ingredientData: IngredientCreate = {
      name: formData.name,
      sku: formData.sku || null,
      barcode: formData.barcode || null,
      brand: formData.brand || null,
      description: formData.description || '',
      category: formData.category,
      unit_of_measure: formData.unit_of_measure,
      package_size: formData.package_size ? Number(formData.package_size) : null,
      standard_cost: formData.standard_cost ? Number(formData.standard_cost) : null,
      low_stock_threshold: Number(formData.low_stock_threshold),
      reorder_point: Number(formData.reorder_point),
      reorder_quantity: Number(formData.reorder_quantity),
      max_stock_level: formData.max_stock_level ? Number(formData.max_stock_level) : null,
      shelf_life_days: formData.shelf_life_days ? Number(formData.shelf_life_days) : null,
      is_perishable: formData.is_perishable === 'true' || formData.is_perishable === true
    };

    setLoading(true);
    try {
      if (onCreateIngredient) {
        await onCreateIngredient(ingredientData);
      }
    } catch (error) {
      console.error('Error creating ingredient:', error);
      throw error; // Let AddModal handle error display
    } finally {
      setLoading(false);
    }
  };

  const statusConfig = {
    color: statusColors.inProgress.primary,
    text: t('inventory:actions.add_item', 'Nuevo Artículo'),
    icon: Plus,
    isCritical: false,
    isHighlight: true
  };

  const sections = [
    {
      title: t('inventory:forms.item_details', 'Información Básica'),
      icon: Package,
      fields: [
        {
          label: t('inventory:fields.name', 'Nombre'),
          name: 'name',
          type: 'text' as const,
          required: true,
          placeholder: t('inventory:validation.name_required', 'Ej: Harina de trigo 000'),
          validation: (value: string | number) => {
            const str = String(value).trim();
            return str.length < 2 ? t('inventory:validation.name_required', 'El nombre debe tener al menos 2 caracteres') : null;
          }
        },
        {
          label: t('inventory:fields.sku', 'Código SKU'),
          name: 'sku',
          type: 'text' as const,
          placeholder: 'SKU-001'
        },
        {
          label: t('inventory:fields.barcode', 'Código de Barras'),
          name: 'barcode',
          type: 'text' as const,
          placeholder: '1234567890123'
        },
        {
          label: t('inventory:fields.brand', 'Marca'),
          name: 'brand',
          type: 'text' as const,
          placeholder: 'Molinos'
        },
        {
          label: t('inventory:fields.description', 'Descripción'),
          name: 'description',
          type: 'text' as const,
          placeholder: t('inventory:fields.description', 'Descripción opcional del artículo'),
          span: 2 // Full width
        },
        {
          label: t('inventory:labels.ingredient_category', 'Categoría'),
          name: 'category',
          type: 'select' as const,
          required: true,
          options: categoryOptions,
          placeholder: t('inventory:validation.category_required', 'Seleccionar categoría...')
        },
        {
          label: t('inventory:labels.unit_of_measure', 'Unidad de Medida'),
          name: 'unit_of_measure',
          type: 'select' as const,
          required: true,
          options: unitOptions,
          defaultValue: 'kg'
        },
        {
          label: t('inventory:fields.package_size', 'Tamaño de Paquete'),
          name: 'package_size',
          type: 'number' as const,
          placeholder: '1',
          helpText: 'Tamaño por paquete/unidad'
        },
        {
          label: t('inventory:fields.shelf_life_days', 'Días de Vida Útil'),
          name: 'shelf_life_days',
          type: 'number' as const,
          placeholder: '30',
          helpText: 'Vida útil predeterminada en días'
        },
        {
          label: t('inventory:fields.is_perishable', '¿Es Perecedero?'),
          name: 'is_perishable',
          type: 'select' as const,
          options: [
            { value: 'false', label: 'No' },
            { value: 'true', label: 'Sí' }
          ],
          defaultValue: 'false',
          span: 2 // Full width
        }
      ]
    },
    {
      title: t('inventory:sections.purchase_costs', 'Costos de Compra'),
      icon: Calculator,
      fields: [
        {
          label: t('inventory:fields.standard_cost', 'Costo Estándar'),
          name: 'standard_cost',
          type: 'currency' as const,
          placeholder: '0.00',
          helpText: t('inventory:help.standard_cost', 'Costo objetivo para presupuesto y análisis de variación'),
          validation: (value: string | number) => {
            const num = Number(value);
            return num < 0 ? t('inventory:validation.current_cannot_be_negative', 'El costo no puede ser negativo') : null;
          }
        }
      ]
    },
    {
      title: t('inventory:sections.stock_management', 'Gestión de Stock'),
      icon: Settings,
      fields: [
        {
          label: t('inventory:fields.low_stock_threshold', 'Umbral Stock Bajo'),
          name: 'low_stock_threshold',
          type: 'number' as const,
          required: true,
          placeholder: '10',
          defaultValue: 10,
          validation: (value: string | number) => {
            const num = Number(value);
            return num < 0 ? t('inventory:validation.min_greater_than_zero', 'El umbral debe ser un número positivo') : null;
          }
        },
        {
          label: t('inventory:fields.reorder_point', 'Punto de Reorden'),
          name: 'reorder_point',
          type: 'number' as const,
          required: true,
          placeholder: '20',
          defaultValue: 20,
          validation: (value: string | number) => {
            const num = Number(value);
            return num < 0 ? t('inventory:validation.min_greater_than_zero', 'El punto de reorden debe ser un número positivo') : null;
          }
        },
        {
          label: t('inventory:fields.reorder_quantity', 'Cantidad de Reorden'),
          name: 'reorder_quantity',
          type: 'number' as const,
          required: true,
          placeholder: '50',
          defaultValue: 50,
          validation: (value: string | number) => {
            const num = Number(value);
            return num <= 0 ? t('inventory:validation.min_greater_than_zero', 'La cantidad de reorden debe ser mayor a cero') : null;
          }
        },
        {
          label: t('inventory:fields.max_stock_level', 'Stock Máximo'),
          name: 'max_stock_level',
          type: 'number' as const,
          placeholder: '100',
          validation: (value: string | number) => {
            const num = Number(value);
            return num < 0 ? t('inventory:validation.min_greater_than_zero', 'El stock máximo debe ser un número positivo') : null;
          }
        }
      ]
    },
  ];

  return (
    <AddModal
      isOpen={isOpen}
      onClose={onClose}
      title={t('inventory:forms.add_item', 'Crear Nuevo Artículo')}
      subtitle={t('inventory:subtitle', 'Agregar un nuevo artículo al inventario')}
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      loading={loading}
      onSave={handleSave}
    />
  );
};

export default CreateIngredientModal;