import React, { useState, useEffect } from 'react';
import { Package, Clock, Users, AlertCircle, ChefHat } from 'lucide-react';
import { StatusModal, StatusModalSection, StatusModalField } from '../../ui/StatusModal/StatusModal';
import { Button, Input, Select } from '../../ui';
import {
  ProductionBatchCreate,
  ProductionPriorityEnum
} from '../../../api/types/production';
import { useProductionEnums } from '../../../utils/enumHelpers';
import { useRecipes } from '../../../api/hooks/recipes';
import { useIngredients } from '../../../api/hooks/inventory';
import { useCurrentTenant } from '../../../stores/tenant.store';

interface CreateProductionBatchModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreateBatch?: (batchData: ProductionBatchCreate) => Promise<void>;
}

/**
 * CreateProductionBatchModal - Modal for creating a new production batch
 * Comprehensive form for adding new production batches
 */
export const CreateProductionBatchModal: React.FC<CreateProductionBatchModalProps> = ({
  isOpen,
  onClose,
  onCreateBatch
}) => {
  const productionEnums = useProductionEnums();
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  // API Data
  const { data: recipes = [], isLoading: recipesLoading } = useRecipes(tenantId);
  const { data: ingredients = [], isLoading: ingredientsLoading } = useIngredients(tenantId);

  const [formData, setFormData] = useState<ProductionBatchCreate>({
    product_id: '',
    product_name: '',
    recipe_id: '',
    planned_start_time: '',
    planned_end_time: '',
    planned_quantity: 1,
    planned_duration_minutes: 60,
    priority: ProductionPriorityEnum.MEDIUM,
    is_rush_order: false,
    is_special_recipe: false,
    production_notes: '',
    batch_number: '',
    order_id: '',
    forecast_id: '',
    equipment_used: [],
    staff_assigned: [],
    station_id: ''
  });

  const [isSubmitting, setIsSubmitting] = useState(false);

  // Reset form when modal opens
  useEffect(() => {
    if (isOpen) {
      setFormData({
        product_id: '',
        product_name: '',
        recipe_id: '',
        planned_start_time: '',
        planned_end_time: '',
        planned_quantity: 1,
        planned_duration_minutes: 60,
        priority: ProductionPriorityEnum.MEDIUM,
        is_rush_order: false,
        is_special_recipe: false,
        production_notes: '',
        batch_number: '',
        order_id: '',
        forecast_id: '',
        equipment_used: [],
        staff_assigned: [],
        station_id: ''
      });
    }
  }, [isOpen]);

  // Filter finished products (ingredients that are finished products)
  const finishedProducts = ingredients.filter(ing =>
    ing.type === 'finished_product' ||
    ing.category === 'finished_products' ||
    ing.name.toLowerCase().includes('pan') ||
    ing.name.toLowerCase().includes('pastel') ||
    ing.name.toLowerCase().includes('torta')
  );

  const productOptions = finishedProducts.map(product => ({
    value: product.id,
    label: product.name
  }));

  const recipeOptions = recipes.map(recipe => ({
    value: recipe.id,
    label: recipe.name
  }));

  const handleSubmit = async () => {
    // Validate required fields
    if (!formData.product_name.trim()) {
      alert('El nombre del producto es obligatorio');
      return;
    }

    if (!formData.product_id.trim()) {
      alert('El ID del producto es obligatorio');
      return;
    }

    if (!formData.planned_start_time) {
      alert('La fecha de inicio planificada es obligatoria');
      return;
    }

    if (!formData.planned_end_time) {
      alert('La fecha de fin planificada es obligatoria');
      return;
    }

    if (formData.planned_quantity <= 0) {
      alert('La cantidad planificada debe ser mayor a 0');
      return;
    }

    if (formData.planned_duration_minutes <= 0) {
      alert('La duración planificada debe ser mayor a 0');
      return;
    }

    // Validate that end time is after start time
    const startTime = new Date(formData.planned_start_time);
    const endTime = new Date(formData.planned_end_time);

    if (endTime <= startTime) {
      alert('La fecha de fin debe ser posterior a la fecha de inicio');
      return;
    }

    setIsSubmitting(true);

    try {
      if (onCreateBatch) {
        await onCreateBatch(formData);
      }
      onClose();
    } catch (error) {
      console.error('Error creating production batch:', error);
      alert('Error al crear el lote de producción. Por favor, inténtalo de nuevo.');
    } finally {
      setIsSubmitting(false);
    }
  };

  // Define sections for StatusModal
  const sections: StatusModalSection[] = [
    {
      title: 'Información del Producto',
      icon: Package,
      fields: [
        {
          label: 'Producto a Producir *',
          value: formData.product_id,
          type: 'select',
          editable: true,
          required: true,
          options: productOptions,
          span: 2
        },
        {
          label: 'Receta a Utilizar',
          value: formData.recipe_id || '',
          type: 'select',
          editable: true,
          options: recipeOptions,
          span: 2
        },
        {
          label: 'Número de Lote',
          value: formData.batch_number || '',
          type: 'text',
          editable: true,
          placeholder: 'Se generará automáticamente si se deja vacío'
        }
      ]
    },
    {
      title: 'Planificación de Producción',
      icon: Clock,
      fields: [
        {
          label: 'Inicio Planificado *',
          value: formData.planned_start_time,
          type: 'datetime-local',
          editable: true,
          required: true
        },
        {
          label: 'Fin Planificado *',
          value: formData.planned_end_time,
          type: 'datetime-local',
          editable: true,
          required: true
        },
        {
          label: 'Cantidad Planificada *',
          value: formData.planned_quantity,
          type: 'number',
          editable: true,
          required: true
        },
        {
          label: 'Duración (minutos) *',
          value: formData.planned_duration_minutes,
          type: 'number',
          editable: true,
          required: true
        }
      ]
    },
    {
      title: 'Configuración y Prioridad',
      icon: AlertCircle,
      fields: [
        {
          label: 'Prioridad *',
          value: formData.priority,
          type: 'select',
          editable: true,
          required: true,
          options: productionEnums.getProductionPriorityOptions()
        },
        {
          label: 'Orden Urgente',
          value: formData.is_rush_order ? 'Sí' : 'No',
          type: 'select',
          editable: true,
          options: [
            { label: 'Sí', value: 'true' },
            { label: 'No', value: 'false' }
          ]
        },
        {
          label: 'Receta Especial',
          value: formData.is_special_recipe ? 'Sí' : 'No',
          type: 'select',
          editable: true,
          options: [
            { label: 'Sí', value: 'true' },
            { label: 'No', value: 'false' }
          ]
        }
      ]
    },
    {
      title: 'Recursos y Notas',
      icon: Users,
      fields: [
        {
          label: 'Personal Asignado',
          value: Array.isArray(formData.staff_assigned) ? formData.staff_assigned.join(', ') : '',
          type: 'text',
          editable: true,
          placeholder: 'Separar nombres con comas (opcional)',
          span: 2
        },
        {
          label: 'Notas de Producción',
          value: formData.production_notes || '',
          type: 'text',
          editable: true,
          placeholder: 'Instrucciones especiales, observaciones, etc.',
          span: 2
        }
      ]
    }
  ];

  // Handle field changes
  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number) => {
    // Map section and field indices to form data properties
    switch (sectionIndex) {
      case 0: // Product Information
        switch (fieldIndex) {
          case 0: // Product ID
            const selectedProduct = finishedProducts.find(p => p.id === value);
            setFormData(prev => ({
              ...prev,
              product_id: String(value),
              product_name: selectedProduct?.name || ''
            }));
            break;
          case 1: // Recipe ID
            setFormData(prev => ({ ...prev, recipe_id: String(value) }));
            break;
          case 2: // Batch Number
            setFormData(prev => ({ ...prev, batch_number: String(value) }));
            break;
        }
        break;
      case 1: // Production Planning
        switch (fieldIndex) {
          case 0: // Start Time
            const startTime = String(value);
            setFormData(prev => ({ ...prev, planned_start_time: startTime }));
            // Auto-calculate end time
            if (startTime && formData.planned_duration_minutes > 0) {
              const start = new Date(startTime);
              const end = new Date(start.getTime() + formData.planned_duration_minutes * 60000);
              const endTimeString = end.toISOString().slice(0, 16);
              setFormData(prev => ({ ...prev, planned_end_time: endTimeString }));
            }
            break;
          case 1: // End Time
            setFormData(prev => ({ ...prev, planned_end_time: String(value) }));
            break;
          case 2: // Quantity
            setFormData(prev => ({ ...prev, planned_quantity: Number(value) || 1 }));
            break;
          case 3: // Duration
            const duration = Number(value) || 60;
            setFormData(prev => ({ ...prev, planned_duration_minutes: duration }));
            // Auto-calculate end time
            if (formData.planned_start_time && duration > 0) {
              const start = new Date(formData.planned_start_time);
              const end = new Date(start.getTime() + duration * 60000);
              const endTimeString = end.toISOString().slice(0, 16);
              setFormData(prev => ({ ...prev, planned_end_time: endTimeString }));
            }
            break;
        }
        break;
      case 2: // Configuration
        switch (fieldIndex) {
          case 0: // Priority
            setFormData(prev => ({ ...prev, priority: value as ProductionPriorityEnum }));
            break;
          case 1: // Rush Order
            setFormData(prev => ({ ...prev, is_rush_order: String(value) === 'true' }));
            break;
          case 2: // Special Recipe
            setFormData(prev => ({ ...prev, is_special_recipe: String(value) === 'true' }));
            break;
        }
        break;
      case 3: // Resources and Notes
        switch (fieldIndex) {
          case 0: // Staff Assigned
            const staff = String(value).split(',').map(s => s.trim()).filter(s => s.length > 0);
            setFormData(prev => ({ ...prev, staff_assigned: staff }));
            break;
          case 1: // Production Notes
            setFormData(prev => ({ ...prev, production_notes: String(value) }));
            break;
        }
        break;
    }
  };

  return (
    <StatusModal
      isOpen={isOpen}
      onClose={onClose}
      mode="edit"
      title="Nueva Orden de Producción"
      subtitle="Crear un nuevo lote de producción"
      sections={sections}
      size="xl"
      loading={isSubmitting}
      onFieldChange={handleFieldChange}
      image={undefined}
      onSave={handleSubmit}
      onCancel={onClose}
      showDefaultActions={true}
    />
  );
};

export default CreateProductionBatchModal;