import React, { useState } from 'react';
import { Plus, Package, Euro, Calendar, FileText, Thermometer } from 'lucide-react';
import { EditViewModal } from '../../ui/EditViewModal/EditViewModal';
import { IngredientResponse, StockCreate, ProductionStage } from '../../../api/types/inventory';
import { Button } from '../../ui/Button';
import { useSuppliers } from '../../../api/hooks/suppliers';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useTranslation } from 'react-i18next';
import { statusColors } from '../../../styles/colors';

interface AddStockModalProps {
  isOpen: boolean;
  onClose: () => void;
  ingredient: IngredientResponse;
  onAddStock?: (stockData: StockCreate) => Promise<void>;
  // Wait-for-refetch support
  waitForRefetch?: boolean;
  isRefetching?: boolean;
  onSaveComplete?: () => Promise<void>;
}

/**
 * AddStockModal - Focused modal for adding new stock
 * Streamlined form for quick stock entry
 */
export const AddStockModal: React.FC<AddStockModalProps> = ({
  isOpen,
  onClose,
  ingredient,
  onAddStock,
  waitForRefetch,
  isRefetching,
  onSaveComplete
}) => {
  const [formData, setFormData] = useState<Partial<StockCreate>>({
    ingredient_id: ingredient.id,
    current_quantity: 0,
    unit_cost: Number(ingredient.average_cost) || 0,
    expiration_date: '',
    production_stage: ProductionStage.RAW_INGREDIENT,
    batch_number: '',
    supplier_id: '',
    quality_status: 'good',
    storage_location: '',
    warehouse_zone: '',
    requires_refrigeration: 'no',
    requires_freezing: 'no',
    storage_temperature_min: undefined,
    storage_temperature_max: undefined,
    storage_humidity_max: undefined,
    shelf_life_days: undefined,
    storage_instructions: '',
    notes: ''
  });

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

  // Get current tenant and fetch suppliers
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  const { data: suppliersData } = useSuppliers(tenantId, {
    limit: 100
  }, {
    enabled: !!tenantId
  });
  const suppliers = (suppliersData || []).filter(supplier => supplier.status === 'active');

  // Get translations
  const { t } = useTranslation(['inventory', 'common']);

  // Get production stage options using direct i18n
  const productionStageOptions = Object.values(ProductionStage).map(value => ({
    value,
    label: t(`inventory:enums.production_stage.${value}`)
  }));

  // Create supplier options for select
  const supplierOptions = [
    { value: '', label: 'Sin proveedor asignado' },
    ...suppliers.map(supplier => ({
      value: supplier.id,
      label: `${supplier.name} (${supplier.supplier_code || 'Sin código'})`
    }))
  ];

  // Create quality status options (matches backend: good, damaged, expired, quarantined)
  const qualityStatusOptions = [
    { value: 'good', label: 'Bueno' },
    { value: 'damaged', label: 'Dañado' },
    { value: 'expired', label: 'Vencido' },
    { value: 'quarantined', label: 'En Cuarentena' }
  ];

  // Create storage location options (predefined common locations)
  const storageLocationOptions = [
    { value: '', label: 'Sin ubicación específica' },
    { value: 'estante-a1', label: 'Estante A-1' },
    { value: 'estante-a2', label: 'Estante A-2' },
    { value: 'estante-a3', label: 'Estante A-3' },
    { value: 'estante-b1', label: 'Estante B-1' },
    { value: 'estante-b2', label: 'Estante B-2' },
    { value: 'frigorifico', label: 'Frigorífico' },
    { value: 'congelador', label: 'Congelador' },
    { value: 'almacen-principal', label: 'Almacén Principal' },
    { value: 'zona-recepcion', label: 'Zona de Recepción' }
  ];

  // Create warehouse zone options
  const warehouseZoneOptions = [
    { value: '', label: 'Sin zona específica' },
    { value: 'zona-a', label: 'Zona A' },
    { value: 'zona-b', label: 'Zona B' },
    { value: 'zona-c', label: 'Zona C' },
    { value: 'refrigerado', label: 'Refrigerado' },
    { value: 'congelado', label: 'Congelado' },
    { value: 'ambiente', label: 'Temperatura Ambiente' }
  ];

  // Create refrigeration requirement options
  const refrigerationOptions = [
    { value: 'no', label: 'No requiere refrigeración' },
    { value: 'yes', label: 'Requiere refrigeración' },
    { value: 'recommended', label: 'Refrigeración recomendada' }
  ];

  // Create freezing requirement options
  const freezingOptions = [
    { value: 'no', label: 'No requiere congelación' },
    { value: 'yes', label: 'Requiere congelación' },
    { value: 'recommended', label: 'Congelación recomendada' }
  ];

  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number | boolean) => {
    const fieldMappings = [
      // Basic Stock Information section
      ['current_quantity', 'unit_cost', 'expiration_date', 'production_stage'],
      // Additional Information section
      ['batch_number', 'supplier_id', 'quality_status', 'storage_location', 'warehouse_zone', 'notes'],
      // Storage Requirements section
      ['requires_refrigeration', 'requires_freezing', 'storage_temperature_min', 'storage_temperature_max', 'storage_humidity_max', 'shelf_life_days', 'storage_instructions']
    ];

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

  const handleSave = async () => {
    if (!formData.current_quantity || formData.current_quantity <= 0) {
      alert('Por favor, ingresa una cantidad válida');
      return;
    }

    if (!formData.unit_cost || formData.unit_cost <= 0) {
      alert('Por favor, ingresa un precio unitario válido');
      return;
    }

    setLoading(true);
    try {
      const stockData: StockCreate = {
        ingredient_id: ingredient.id,
        current_quantity: Number(formData.current_quantity),
        unit_cost: Number(formData.unit_cost),
        expiration_date: formData.expiration_date || undefined,
        production_stage: formData.production_stage || ProductionStage.RAW_INGREDIENT,
        batch_number: formData.batch_number || undefined,
        supplier_id: formData.supplier_id || undefined,
        quality_status: formData.quality_status || 'good',
        storage_location: formData.storage_location || undefined,
        warehouse_zone: formData.warehouse_zone || undefined,
        requires_refrigeration: formData.requires_refrigeration === 'yes',
        requires_freezing: formData.requires_freezing === 'yes',
        storage_temperature_min: formData.storage_temperature_min ? Number(formData.storage_temperature_min) : undefined,
        storage_temperature_max: formData.storage_temperature_max ? Number(formData.storage_temperature_max) : undefined,
        storage_humidity_max: formData.storage_humidity_max ? Number(formData.storage_humidity_max) : undefined,
        shelf_life_days: formData.shelf_life_days ? Number(formData.shelf_life_days) : undefined,
        storage_instructions: formData.storage_instructions || undefined,
        notes: formData.notes || undefined
      };

      if (onAddStock) {
        await onAddStock(stockData);
      }

      // If waitForRefetch is enabled, trigger refetch and wait
      if (waitForRefetch && onSaveComplete) {
        await onSaveComplete();

        // Wait for refetch to complete
        const startTime = Date.now();
        const refetchTimeout = 3000;

        await new Promise<void>((resolve) => {
          const interval = setInterval(() => {
            const elapsed = Date.now() - startTime;

            if (elapsed >= refetchTimeout) {
              clearInterval(interval);
              console.warn('Refetch timeout reached for stock addition');
              resolve();
              return;
            }

            if (!isRefetching) {
              clearInterval(interval);
              resolve();
            }
          }, 100);
        });
      }

      // Reset form
      setFormData({
        ingredient_id: ingredient.id,
        current_quantity: 0,
        unit_cost: Number(ingredient.average_cost) || 0,
        expiration_date: '',
        production_stage: ProductionStage.RAW_INGREDIENT,
        batch_number: '',
        supplier_id: '',
        quality_status: 'good',
        storage_location: '',
        warehouse_zone: '',
        requires_refrigeration: 'no',
        requires_freezing: 'no',
        storage_temperature_min: undefined,
        storage_temperature_max: undefined,
        storage_humidity_max: undefined,
        shelf_life_days: undefined,
        storage_instructions: '',
        notes: ''
      });

      onClose();
    } catch (error) {
      console.error('Error adding stock:', error);
      alert('Error al agregar stock. Por favor, intenta de nuevo.');
    } finally {
      setLoading(false);
    }
  };

  const currentStock = Number(ingredient.current_stock) || 0;
  const newTotal = currentStock + (Number(formData.current_quantity) || 0);
  const totalValue = (Number(formData.current_quantity) || 0) * (Number(formData.unit_cost) || 0);

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

  const sections = [
    {
      title: 'Información del Stock',
      icon: Package,
      fields: [
        {
          label: `Cantidad (${ingredient.unit_of_measure})`,
          value: formData.current_quantity || 0,
          type: 'number' as const,
          editable: true,
          required: true,
          placeholder: 'Ej: 50'
        },
        {
          label: 'Precio Unitario',
          value: formData.unit_cost || 0,
          type: 'currency' as const,
          editable: true,
          required: true,
          placeholder: 'Ej: 2.50'
        },
        {
          label: 'Fecha de Vencimiento',
          value: formData.expiration_date || '',
          type: 'date' as const,
          editable: true
        },
        {
          label: 'Etapa de Producción',
          value: formData.production_stage || ProductionStage.RAW_INGREDIENT,
          type: 'select' as const,
          editable: true,
          options: productionStageOptions
        }
      ]
    },
    {
      title: 'Información Adicional',
      icon: FileText,
      fields: [
        {
          label: 'Número de Lote',
          value: formData.batch_number || '',
          type: 'text' as const,
          editable: true,
          placeholder: 'Ej: LOTE2024001'
        },
        {
          label: 'Proveedor',
          value: formData.supplier_id || '',
          type: 'select' as const,
          editable: true,
          placeholder: 'Seleccionar proveedor',
          options: supplierOptions
        },
        {
          label: 'Estado de Calidad',
          value: formData.quality_status || 'good',
          type: 'select' as const,
          editable: true,
          options: qualityStatusOptions
        },
        {
          label: 'Ubicación de Almacenamiento',
          value: formData.storage_location || '',
          type: 'select' as const,
          editable: true,
          placeholder: 'Seleccionar ubicación',
          options: storageLocationOptions
        },
        {
          label: 'Zona de Almacén',
          value: formData.warehouse_zone || '',
          type: 'select' as const,
          editable: true,
          placeholder: 'Seleccionar zona',
          options: warehouseZoneOptions
        },
        {
          label: 'Notas',
          value: formData.notes || '',
          type: 'text' as const,
          editable: true,
          placeholder: 'Observaciones adicionales...',
          span: 2 as const
        }
      ]
    },
    {
      title: 'Requisitos de Almacenamiento',
      icon: Thermometer,
      fields: [
        {
          label: 'Requiere Refrigeración',
          value: formData.requires_refrigeration || 'no',
          type: 'select' as const,
          editable: true,
          options: refrigerationOptions
        },
        {
          label: 'Requiere Congelación',
          value: formData.requires_freezing || 'no',
          type: 'select' as const,
          editable: true,
          options: freezingOptions
        },
        {
          label: 'Temperatura Mínima (°C)',
          value: formData.storage_temperature_min || '',
          type: 'number' as const,
          editable: true,
          placeholder: 'Ej: 2'
        },
        {
          label: 'Temperatura Máxima (°C)',
          value: formData.storage_temperature_max || '',
          type: 'number' as const,
          editable: true,
          placeholder: 'Ej: 8'
        },
        {
          label: 'Humedad Máxima (%)',
          value: formData.storage_humidity_max || '',
          type: 'number' as const,
          editable: true,
          placeholder: 'Ej: 60'
        },
        {
          label: 'Vida Útil (días)',
          value: formData.shelf_life_days || '',
          type: 'number' as const,
          editable: true,
          placeholder: 'Ej: 30'
        },
        {
          label: 'Instrucciones de Almacenamiento',
          value: formData.storage_instructions || '',
          type: 'text' as const,
          editable: true,
          placeholder: 'Instrucciones específicas...',
          span: 2 as const
        }
      ]
    }
  ];

  const actions = [
    {
      label: 'Cancelar',
      variant: 'outline' as const,
      onClick: onClose,
      disabled: loading
    },
    {
      label: 'Agregar Stock',
      variant: 'primary' as const,
      onClick: handleSave,
      disabled: loading || !formData.current_quantity || !formData.unit_cost,
      loading
    }
  ];

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={onClose}
      mode={mode}
      onModeChange={setMode}
      title={ingredient.name}
      subtitle={`${ingredient.category} • ${currentStock} ${ingredient.unit_of_measure}`}
      statusIndicator={statusConfig}
      sections={sections}
      actions={actions}
      onFieldChange={handleFieldChange}
      onSave={handleSave}
      size="lg"
      loading={loading}
      showDefaultActions={false}
    />
  );
};

export default AddStockModal;