import React, { useState } from 'react';
import { Package, AlertTriangle, CheckCircle, Clock, Euro, Edit, Info, Thermometer, Calendar, Tag, Save, X, TrendingUp } from 'lucide-react';
import { StatusModal } from '../../ui/StatusModal/StatusModal';
import { IngredientResponse } 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>;
}

/**
 * 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
}) => {
  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) {
      await onSave(editData);
      setIsEditing(false);
      setEditData({});
    }
  };

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

  const currentData = isEditing ? editData : ingredient;

  const sections = [
    {
      title: 'Información Básica',
      icon: Info,
      fields: [
        {
          label: 'Nombre',
          value: currentData.name || '',
          highlight: true,
          span: 2 as const,
          editable: true,
          required: true
        },
        {
          label: 'Descripción',
          value: currentData.description || '',
          span: 2 as const,
          editable: true,
          placeholder: 'Descripción del producto'
        },
        {
          label: 'Categoría',
          value: currentData.category || '',
          span: 1 as const,
          editable: true,
          required: true
        },
        {
          label: 'Subcategoría',
          value: currentData.subcategory || '',
          span: 1 as const,
          editable: true,
          placeholder: 'Subcategoría'
        },
        {
          label: 'Marca',
          value: currentData.brand || '',
          span: 1 as const,
          editable: true,
          placeholder: 'Marca del producto'
        },
        {
          label: 'Tipo de Producto',
          value: currentData.product_type || '',
          span: 1 as const,
          editable: true,
          placeholder: 'Tipo de producto'
        }
      ]
    },
    {
      title: 'Especificaciones',
      icon: Package,
      fields: [
        {
          label: 'Unidad de Medida',
          value: currentData.unit_of_measure || '',
          span: 1 as const,
          editable: true,
          required: true,
          placeholder: 'kg, litros, unidades, etc.'
        },
        {
          label: 'Tamaño del Paquete',
          value: currentData.package_size || '',
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: 'Tamaño del paquete'
        },
        {
          label: 'Es Perecedero',
          value: currentData.is_perishable ? 'Sí' : 'No',
          span: 1 as const,
          editable: true,
          type: 'select' as const,
          options: [
            { label: 'Sí', value: 'true' },
            { label: 'No', value: 'false' }
          ]
        },
        {
          label: 'Es de Temporada',
          value: currentData.is_seasonal ? 'Sí' : 'No',
          span: 1 as const,
          editable: true,
          type: 'select' as const,
          options: [
            { label: 'Sí', value: 'true' },
            { label: 'No', value: 'false' }
          ]
        }
      ]
    },
    {
      title: 'Costos y Precios',
      icon: Euro,
      fields: [
        {
          label: 'Costo Promedio',
          value: Number(currentData.average_cost) || 0,
          type: 'currency' as const,
          span: 1 as const,
          editable: true,
          placeholder: '0.00'
        },
        {
          label: 'Ú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: 'Costo Estándar',
          value: Number(currentData.standard_cost) || 0,
          type: 'currency' as const,
          span: 2 as const,
          editable: true,
          placeholder: '0.00'
        }
      ]
    },
    {
      title: 'Parámetros de Inventario',
      icon: TrendingUp,
      fields: [
        {
          label: 'Umbral Stock Bajo',
          value: currentData.low_stock_threshold || 0,
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: 'Cantidad mínima antes de alerta'
        },
        {
          label: 'Punto de Reorden',
          value: currentData.reorder_point || 0,
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: 'Punto para reordenar'
        },
        {
          label: 'Cantidad de Reorden',
          value: currentData.reorder_quantity || 0,
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: 'Cantidad a reordenar'
        },
        {
          label: 'Stock Máximo',
          value: currentData.max_stock_level || '',
          span: 1 as const,
          editable: true,
          type: 'number' as const,
          placeholder: 'Cantidad máxima permitida'
        }
      ]
    }
  ];

  // Actions based on edit mode
  const actions = [];
  if (isEditing) {
    actions.push(
      {
        label: 'Cancelar',
        icon: X,
        variant: 'outline' as const,
        onClick: handleCancel
      },
      {
        label: 'Guardar',
        icon: Save,
        variant: 'primary' as const,
        onClick: handleSave
      }
    );
  } else if (onSave) {
    actions.push({
      label: 'Editar',
      icon: Edit,
      variant: 'primary' as const,
      onClick: handleEdit
    });
  }

  // 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 = value;

    // Handle boolean fields
    if (fieldName === 'is_perishable' || fieldName === 'is_seasonal') {
      processedValue = value === 'true';
    }

    // Handle numeric fields
    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 (
    <StatusModal
      isOpen={isOpen}
      onClose={onClose}
      mode={isEditing ? "edit" : "view"}
      title={`${isEditing ? 'Editar' : 'Detalles'}: ${ingredient.name}`}
      subtitle={`${ingredient.category} • Información del artículo`}
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      showDefaultActions={false}
      actions={actions}
      onFieldChange={handleFieldChange}
    />
  );
};

export default ShowInfoModal;