import React from 'react';
import { Clock, TrendingDown, Package, AlertCircle, RotateCcw, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { EditViewModal } from '../../ui/EditViewModal/EditViewModal';
import { IngredientResponse, StockMovementResponse } from '../../../api/types/inventory';
import { formatters } from '../../ui/Stats/StatsPresets';
import { statusColors } from '../../../styles/colors';

interface StockHistoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  ingredient: IngredientResponse;
  movements: StockMovementResponse[];
  loading?: boolean;
}

/**
 * StockHistoryModal - Dedicated modal for stock movement history
 * Shows only the movements list in a clean, focused interface
 */
export const StockHistoryModal: React.FC<StockHistoryModalProps> = ({
  isOpen,
  onClose,
  ingredient,
  movements = [],
  loading = false
}) => {
  const { t } = useTranslation(['inventory', 'common']);

  // Helper function to get translated category display name
  const getCategoryDisplayName = (category?: string | null): string => {
    if (!category) return t('categories.all', 'Sin categoría');

    // Try ingredient category translation first
    const ingredientTranslation = t(`enums.ingredient_category.${category}`, { defaultValue: '' });
    if (ingredientTranslation) return ingredientTranslation;

    // Try product category translation
    const productTranslation = t(`enums.product_category.${category}`, { defaultValue: '' });
    if (productTranslation) return productTranslation;

    // Fallback to raw category if no translation found
    return category;
  };

  // Get movement type display info
  const getMovementTypeInfo = (type: string, quantity: number) => {
    const absQuantity = Math.abs(quantity);
    
    // Determine if movement should be positive or negative based on type
    // Some movement types have fixed direction regardless of quantity sign
    let isPositive: boolean;
    let displayQuantity: string;
    
    switch (type) {
      case 'PURCHASE':
      case 'INITIAL_STOCK':
        isPositive = true;
        displayQuantity = `+${absQuantity}`;
        break;
      case 'PRODUCTION_USE':
      case 'WASTE':
        isPositive = false;
        displayQuantity = `-${absQuantity}`;
        break;
      case 'ADJUSTMENT':
      case 'TRANSFORMATION':
        // For these types, follow the actual quantity direction
        isPositive = quantity > 0;
        displayQuantity = quantity > 0 ? `+${absQuantity}` : `-${absQuantity}`;
        break;
      default:
        // For any other types, follow the quantity direction
        isPositive = quantity > 0;
        displayQuantity = quantity > 0 ? `+${absQuantity}` : `-${absQuantity}`;
    }

    switch (type) {
      case 'PURCHASE':
        return {
          type: 'Compra',
          icon: Package,
          color: statusColors.completed.primary,
          isPositive: true,
          quantity: displayQuantity
        };
      case 'PRODUCTION_USE':
        return {
          type: 'Uso en Producción',
          icon: TrendingDown,
          color: statusColors.pending.primary,
          isPositive: false,
          quantity: displayQuantity
        };
      case 'ADJUSTMENT':
        return {
          type: 'Ajuste',
          icon: AlertCircle,
          color: statusColors.inProgress.primary,
          isPositive,
          quantity: displayQuantity
        };
      case 'WASTE':
        return {
          type: 'Desperdicio',
          icon: X,
          color: statusColors.out.primary,
          isPositive: false,
          quantity: displayQuantity
        };
      case 'TRANSFORMATION':
        return {
          type: 'Transformación',
          icon: RotateCcw,
          color: statusColors.low.primary,
          isPositive,
          quantity: displayQuantity
        };
      case 'INITIAL_STOCK':
        return {
          type: 'Stock Inicial',
          icon: Package,
          color: statusColors.normal.primary,
          isPositive: true,
          quantity: displayQuantity
        };
      default:
        return {
          type: t('enums.stock_movement_type.OTHER', 'Otro'),
          icon: Package,
          color: statusColors.other.primary,
          isPositive,
          quantity: displayQuantity
        };
    }
  };

  // Process movements for display
  const recentMovements = movements.slice(0, 20).map(movement => {
    const movementInfo = getMovementTypeInfo(movement.movement_type, Number(movement.quantity));

    return {
      id: movement.id,
      ...movementInfo,
      date: movement.movement_date ? new Date(movement.movement_date).toLocaleDateString('es-ES') : 'Sin fecha',
      cost: movement.unit_cost ? formatters.currency(Number(movement.unit_cost)) : '-',
      reference: movement.reference_number || '-',
      notes: movement.notes || '-',
      quantityBefore: Number(movement.quantity_before) || 0,
      quantityAfter: Number(movement.quantity_after) || 0
    };
  });

  const statusConfig = {
    color: statusColors.inProgress.primary,
    text: `${movements.length} movimientos`,
    icon: Clock
  };

  // Create movements list display
  const movementsList = recentMovements.length > 0 ? (
    <div className="space-y-3 max-h-96 overflow-y-auto">
      {recentMovements.map((movement) => {
        const MovementIcon = movement.icon;
        return (
          <div
            key={movement.id}
            className="flex items-center gap-3 p-4 bg-[var(--surface-secondary)] rounded-lg hover:bg-[var(--surface-tertiary)] transition-colors border border-[var(--border-primary)]"
          >
            {/* Icon and type */}
            <div
              className="flex-shrink-0 p-2 rounded-lg"
              style={{ backgroundColor: `${movement.color}15` }}
            >
              <MovementIcon
                className="w-5 h-5"
                style={{ color: movement.color }}
              />
            </div>

            {/* Main content */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-between">
                <span className="font-medium text-[var(--text-primary)]">
                  {movement.type}
                </span>
                <span
                  className="font-bold text-lg"
                  style={{
                    color: movement.isPositive
                      ? statusColors.completed.primary
                      : statusColors.out.primary
                  }}
                >
                  {movement.quantity}
                </span>
              </div>

              <div className="flex items-center justify-between text-sm text-[var(--text-secondary)] mt-1">
                <span>{movement.date}</span>
                <span>{movement.cost}</span>
              </div>

              {movement.reference !== '-' && (
                <div className="text-xs text-[var(--text-tertiary)] mt-1">
                  Ref: {movement.reference}
                </div>
              )}

              {movement.notes !== '-' && (
                <div className="text-xs text-[var(--text-secondary)] mt-1 truncate">
                  {movement.notes}
                </div>
              )}
            </div>

            {/* Stock levels */}
            <div className="text-right text-sm">
              <div className="text-[var(--text-tertiary)]">
                {movement.quantityBefore} → {movement.quantityAfter}
              </div>
              <div className="text-xs text-[var(--text-tertiary)]">
                {ingredient.unit_of_measure}
              </div>
            </div>
          </div>
        );
      })}

      {movements.length > 20 && (
        <div className="text-center text-sm text-[var(--text-secondary)] mt-4 p-3 bg-[var(--surface-secondary)] rounded-lg">
          Y {movements.length - 20} movimientos más...
        </div>
      )}
    </div>
  ) : (
    <div className="text-center py-12 text-[var(--text-secondary)]">
      <Clock className="w-16 h-16 mx-auto mb-4 opacity-30" />
      <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
        No hay movimientos registrados
      </h3>
      <p className="text-sm">
        Los movimientos de stock aparecerán aquí cuando se agregue o use inventario
      </p>
    </div>
  );

  const sections = [
    {
      title: 'Historial de Movimientos',
      icon: Clock,
      fields: [
        {
          label: '',
          value: movementsList,
          span: 2 as const
        }
      ]
    }
  ];

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={onClose}
      mode="view"
      title={ingredient.name}
      subtitle={`${getCategoryDisplayName(ingredient.category)} • ${movements.length} movimientos`}
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      loading={loading}
      showDefaultActions={false}
    />
  );
};

export default StockHistoryModal;
