/**
 * Helper utilities for ingredient management
 */

// Levenshtein distance calculation for fuzzy string matching
export function levenshteinDistance(str1: string, str2: string): number {
  const s1 = str1.toLowerCase().trim();
  const s2 = str2.toLowerCase().trim();

  const matrix: number[][] = [];

  // Initialize first column
  for (let i = 0; i <= s2.length; i++) {
    matrix[i] = [i];
  }

  // Initialize first row
  for (let j = 0; j <= s1.length; j++) {
    matrix[0][j] = j;
  }

  // Fill the matrix
  for (let i = 1; i <= s2.length; i++) {
    for (let j = 1; j <= s1.length; j++) {
      if (s2.charAt(i - 1) === s1.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1];
      } else {
        matrix[i][j] = Math.min(
          matrix[i - 1][j - 1] + 1, // substitution
          matrix[i][j - 1] + 1,     // insertion
          matrix[i - 1][j] + 1      // deletion
        );
      }
    }
  }

  return matrix[s2.length][s1.length];
}

// Calculate similarity percentage (0-100)
export function calculateSimilarity(str1: string, str2: string): number {
  const maxLen = Math.max(str1.length, str2.length);
  if (maxLen === 0) return 100;

  const distance = levenshteinDistance(str1, str2);
  return Math.round(((maxLen - distance) / maxLen) * 100);
}

// Find similar ingredient names
export function findSimilarIngredients(
  name: string,
  existingIngredients: { id: string; name: string }[],
  similarityThreshold: number = 70
): Array<{ id: string; name: string; similarity: number }> {
  if (!name || name.trim().length < 3) return [];

  const similar = existingIngredients
    .map(ingredient => ({
      ...ingredient,
      similarity: calculateSimilarity(name, ingredient.name)
    }))
    .filter(item => item.similarity >= similarityThreshold && item.similarity < 100)
    .sort((a, b) => b.similarity - a.similarity);

  return similar.slice(0, 3); // Return top 3 matches
}

// Smart category suggestions based on ingredient name
const categoryPatterns: Record<string, string[]> = {
  'Baking Ingredients': [
    'harina', 'flour', 'levadura', 'yeast', 'polvo de hornear', 'baking powder',
    'bicarbonato', 'baking soda', 'azúcar', 'sugar', 'sal', 'salt', 'masa',
    'dough', 'hojaldre', 'puff pastry', 'chocolate', 'cacao', 'cocoa', 'vainilla',
    'vanilla', 'canela', 'cinnamon'
  ],
  'Dairy': [
    'leche', 'milk', 'mantequilla', 'butter', 'queso', 'cheese', 'crema', 'cream',
    'nata', 'yogur', 'yogurt', 'requesón', 'cottage cheese', 'ricotta'
  ],
  'Fruits': [
    'manzana', 'apple', 'fresa', 'strawberry', 'plátano', 'banana', 'naranja',
    'orange', 'limón', 'lemon', 'frambuesa', 'raspberry', 'arándano', 'blueberry',
    'cereza', 'cherry', 'pera', 'pear', 'durazno', 'peach', 'melocotón', 'mango',
    'piña', 'pineapple', 'kiwi', 'uva', 'grape'
  ],
  'Vegetables': [
    'tomate', 'tomato', 'lechuga', 'lettuce', 'cebolla', 'onion', 'zanahoria',
    'carrot', 'papa', 'patata', 'potato', 'pimiento', 'pepper', 'espinaca',
    'spinach', 'brócoli', 'broccoli', 'calabacín', 'zucchini', 'berenjena',
    'eggplant', 'aguacate', 'avocado'
  ],
  'Meat': [
    'pollo', 'chicken', 'carne', 'beef', 'cerdo', 'pork', 'jamón', 'ham',
    'tocino', 'bacon', 'salchicha', 'sausage', 'pavo', 'turkey', 'cordero', 'lamb'
  ],
  'Seafood': [
    'pescado', 'fish', 'salmón', 'salmon', 'atún', 'tuna', 'camarón', 'shrimp',
    'langostino', 'prawn', 'mejillón', 'mussel', 'almeja', 'clam', 'calamar',
    'squid', 'pulpo', 'octopus'
  ],
  'Spices': [
    'pimienta', 'pepper', 'orégano', 'oregano', 'albahaca', 'basil', 'tomillo',
    'thyme', 'romero', 'rosemary', 'perejil', 'parsley', 'cilantro', 'coriander',
    'comino', 'cumin', 'paprika', 'pimentón', 'nuez moscada', 'nutmeg', 'jengibre',
    'ginger', 'ajo', 'garlic', 'clavo', 'clove'
  ]
};

export function suggestCategory(ingredientName: string): string | null {
  if (!ingredientName || ingredientName.trim().length < 2) return null;

  const nameLower = ingredientName.toLowerCase().trim();

  // Check each category's patterns
  for (const [category, patterns] of Object.entries(categoryPatterns)) {
    for (const pattern of patterns) {
      if (nameLower.includes(pattern) || pattern.includes(nameLower)) {
        return category;
      }
    }
  }

  return null;
}

// Quick templates for common bakery ingredients
export interface IngredientTemplate {
  name: string;
  category: string;
  unit_of_measure: string;
  icon: string;
  estimated_shelf_life_days?: number;
  requires_refrigeration?: boolean;
  requires_freezing?: boolean;
}

export const commonIngredientTemplates: IngredientTemplate[] = [
  {
    name: 'Harina de Trigo',
    category: 'Baking Ingredients',
    unit_of_measure: 'kg',
    icon: '🌾',
    estimated_shelf_life_days: 180,
    requires_refrigeration: false,
    requires_freezing: false,
  },
  {
    name: 'Mantequilla',
    category: 'Dairy',
    unit_of_measure: 'kg',
    icon: '🧈',
    estimated_shelf_life_days: 30,
    requires_refrigeration: true,
    requires_freezing: false,
  },
  {
    name: 'Azúcar',
    category: 'Baking Ingredients',
    unit_of_measure: 'kg',
    icon: '🍬',
    estimated_shelf_life_days: 365,
    requires_refrigeration: false,
    requires_freezing: false,
  },
  {
    name: 'Huevos',
    category: 'Dairy',
    unit_of_measure: 'units',
    icon: '🥚',
    estimated_shelf_life_days: 21,
    requires_refrigeration: true,
    requires_freezing: false,
  },
  {
    name: 'Levadura',
    category: 'Baking Ingredients',
    unit_of_measure: 'kg',
    icon: '🍞',
    estimated_shelf_life_days: 90,
    requires_refrigeration: true,
    requires_freezing: false,
  },
  {
    name: 'Leche',
    category: 'Dairy',
    unit_of_measure: 'L',
    icon: '🥛',
    estimated_shelf_life_days: 7,
    requires_refrigeration: true,
    requires_freezing: false,
  },
  {
    name: 'Chocolate',
    category: 'Baking Ingredients',
    unit_of_measure: 'kg',
    icon: '🍫',
    estimated_shelf_life_days: 180,
    requires_refrigeration: false,
    requires_freezing: false,
  },
  {
    name: 'Vainilla (Extracto)',
    category: 'Baking Ingredients',
    unit_of_measure: 'ml',
    icon: '🌸',
    estimated_shelf_life_days: 365,
    requires_refrigeration: false,
    requires_freezing: false,
  },
  {
    name: 'Sal',
    category: 'Baking Ingredients',
    unit_of_measure: 'kg',
    icon: '🧂',
    estimated_shelf_life_days: 9999,
    requires_refrigeration: false,
    requires_freezing: false,
  },
  {
    name: 'Crema de Leche',
    category: 'Dairy',
    unit_of_measure: 'L',
    icon: '🥛',
    estimated_shelf_life_days: 14,
    requires_refrigeration: true,
    requires_freezing: false,
  },
];
