import React, { useState } from 'react';
import { Plus, Package, Calculator, Settings } from 'lucide-react';
import { StatusModal } from '../../ui/StatusModal/StatusModal';
import { IngredientCreate, UnitOfMeasure, IngredientCategory, ProductCategory } from '../../../api/types/inventory';
import { useInventoryEnums } from '../../../utils/inventoryEnumHelpers';
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 [formData, setFormData] = useState<IngredientCreate>({
    name: '',
    description: '',
    category: '',
    unit_of_measure: 'kg',
    low_stock_threshold: 10,
    reorder_point: 20,
    max_stock_level: 100,
    is_seasonal: false,
    average_cost: 0,
    notes: ''
  });

  const [loading, setLoading] = useState(false);
  const [mode, setMode] = useState<'overview' | 'edit'>('edit');

  // Get enum options using helpers
  const inventoryEnums = useInventoryEnums();

  // Combine ingredient and product categories
  const categoryOptions = [
    ...inventoryEnums.getIngredientCategoryOptions(),
    ...inventoryEnums.getProductCategoryOptions()
  ];

  const unitOptions = inventoryEnums.getUnitOfMeasureOptions();

  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number | boolean) => {
    // Map field positions to form data fields
    const fieldMappings = [
      // Basic Information section
      ['name', 'description', 'category', 'unit_of_measure'],
      // Cost and Quantities section
      ['average_cost', 'low_stock_threshold', 'reorder_point', 'max_stock_level'],
      // Additional Information section
      ['notes']
    ];

    const fieldName = fieldMappings[sectionIndex]?.[fieldIndex] as keyof IngredientCreate;
    if (fieldName) {
      setFormData(prev => ({
        ...prev,
        [fieldName]: value
      }));
    }
  };

  const handleSave = async () => {
    // Validation
    if (!formData.name?.trim()) {
      alert('El nombre es requerido');
      return;
    }

    if (!formData.category) {
      alert('La categoría es requerida');
      return;
    }

    if (!formData.unit_of_measure) {
      alert('La unidad de medida es requerida');
      return;
    }

    if (!formData.low_stock_threshold || formData.low_stock_threshold < 0) {
      alert('El umbral de stock bajo debe ser un número positivo');
      return;
    }

    if (!formData.reorder_point || formData.reorder_point < 0) {
      alert('El punto de reorden debe ser un número positivo');
      return;
    }

    if (formData.reorder_point <= formData.low_stock_threshold) {
      alert('El punto de reorden debe ser mayor que el umbral de stock bajo');
      return;
    }

    setLoading(true);
    try {
      if (onCreateIngredient) {
        await onCreateIngredient(formData);
      }

      // Reset form
      setFormData({
        name: '',
        description: '',
        category: '',
        unit_of_measure: 'kg',
        low_stock_threshold: 10,
        reorder_point: 20,
        max_stock_level: 100,
        shelf_life_days: undefined,
        requires_refrigeration: false,
        requires_freezing: false,
        is_seasonal: false,
        average_cost: 0,
        notes: ''
      });

      onClose();
    } catch (error) {
      console.error('Error creating ingredient:', error);
      alert('Error al crear el artículo. Por favor, intenta de nuevo.');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    // Reset form to initial values
    setFormData({
      name: '',
      description: '',
      category: '',
      unit_of_measure: 'kg',
      low_stock_threshold: 10,
      reorder_point: 20,
      max_stock_level: 100,
      shelf_life_days: undefined,
      requires_refrigeration: false,
      requires_freezing: false,
      is_seasonal: false,
      average_cost: 0,
      notes: ''
    });
    onClose();
  };

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

  const sections = [
    {
      title: 'Información Básica',
      icon: Package,
      fields: [
        {
          label: 'Nombre',
          value: formData.name,
          type: 'text' as const,
          editable: true,
          required: true,
          placeholder: 'Ej: Harina de trigo 000'
        },
        {
          label: 'Descripción',
          value: formData.description || '',
          type: 'text' as const,
          editable: true,
          placeholder: 'Descripción opcional del artículo'
        },
        {
          label: 'Categoría',
          value: formData.category,
          type: 'select' as const,
          editable: true,
          required: true,
          options: categoryOptions
        },
        {
          label: 'Unidad de Medida',
          value: formData.unit_of_measure,
          type: 'select' as const,
          editable: true,
          required: true,
          options: unitOptions
        }
      ]
    },
    {
      title: 'Costos y Cantidades',
      icon: Calculator,
      fields: [
        {
          label: 'Costo Promedio',
          value: formData.average_cost || 0,
          type: 'currency' as const,
          editable: true,
          placeholder: '0.00'
        },
        {
          label: 'Umbral Stock Bajo',
          value: formData.low_stock_threshold,
          type: 'number' as const,
          editable: true,
          required: true,
          placeholder: '10'
        },
        {
          label: 'Punto de Reorden',
          value: formData.reorder_point,
          type: 'number' as const,
          editable: true,
          required: true,
          placeholder: '20'
        },
        {
          label: 'Stock Máximo',
          value: formData.max_stock_level || 0,
          type: 'number' as const,
          editable: true,
          placeholder: '100'
        }
      ]
    },
    {
      title: 'Información Adicional',
      icon: Settings,
      fields: [
        {
          label: 'Notas',
          value: formData.notes || '',
          type: 'text' as const,
          editable: true,
          placeholder: 'Notas adicionales'
        }
      ]
    }
  ];

  return (
    <StatusModal
      isOpen={isOpen}
      onClose={onClose}
      mode={mode}
      title="Crear Nuevo Artículo"
      subtitle="Agregar un nuevo artículo al inventario"
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      loading={loading}
      showDefaultActions={true}
      onSave={handleSave}
      onCancel={handleCancel}
      onFieldChange={handleFieldChange}
    />
  );
};

export default CreateIngredientModal;