import React, { useState, useMemo } from 'react';
import { Plus, Star, Clock, DollarSign, Package, Eye, Edit, ChefHat, Timer, Euro } from 'lucide-react';
import { Button, Input, Card, StatsGrid, StatusCard, getStatusColor, StatusModal } from '../../../../components/ui';
import { LoadingSpinner } from '../../../../components/shared';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { PageHeader } from '../../../../components/layout';
import { useRecipes, useRecipeStatistics, useCreateRecipe, useUpdateRecipe, useDeleteRecipe } from '../../../../api/hooks/recipes';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import type { RecipeResponse, RecipeCreate, MeasurementUnit } from '../../../../api/types/recipes';
import { CreateRecipeModal } from '../../../../components/domain/recipes';

const RecipesPage: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
  const [selectedRecipe, setSelectedRecipe] = useState<RecipeResponse | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editedRecipe, setEditedRecipe] = useState<Partial<RecipeResponse>>({});

  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  // Mutations
  const createRecipeMutation = useCreateRecipe(tenantId);
  const updateRecipeMutation = useUpdateRecipe(tenantId);
  const deleteRecipeMutation = useDeleteRecipe(tenantId);

  // API Data
  const {
    data: recipes = [],
    isLoading: recipesLoading,
    error: recipesError
  } = useRecipes(tenantId, { search_term: searchTerm || undefined });

  const {
    data: statisticsData,
    isLoading: statisticsLoading
  } = useRecipeStatistics(tenantId);


  const getRecipeStatusConfig = (recipe: RecipeResponse) => {
    const category = recipe.category || 'other';
    const difficulty = recipe.difficulty_level || 1;
    const isSignature = recipe.is_signature_item;
    const categoryConfig = {
      bread: { text: 'Pan', icon: ChefHat },
      pastry: { text: 'Bollería', icon: ChefHat },
      cake: { text: 'Tarta', icon: ChefHat },
      cookie: { text: 'Galleta', icon: ChefHat },
      other: { text: 'Otro', icon: ChefHat },
    };

    const difficultyConfig = {
      1: { icon: '●', label: 'Fácil' },
      2: { icon: '●●', label: 'Medio' },
      3: { icon: '●●●', label: 'Difícil' },
    };

    const categoryInfo = categoryConfig[category as keyof typeof categoryConfig] || categoryConfig.other;
    const difficultyInfo = difficultyConfig[Math.min(difficulty, 3) as keyof typeof difficultyConfig] || difficultyConfig[1];
    
    return {
      color: getStatusColor(category),
      text: categoryInfo.text,
      icon: categoryInfo.icon,
      difficultyIcon: difficultyInfo.icon,
      difficultyLabel: difficultyInfo.label,
      isCritical: false,
      isHighlight: isSignature
    };
  };

  const formatTime = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
  };

  const filteredRecipes = useMemo(() => {
    if (!searchTerm) return recipes;

    const searchLower = searchTerm.toLowerCase();
    return recipes.filter(recipe =>
      recipe.name.toLowerCase().includes(searchLower) ||
      (recipe.description && recipe.description.toLowerCase().includes(searchLower)) ||
      (recipe.category && recipe.category.toLowerCase().includes(searchLower))
    );
  }, [recipes, searchTerm]);

  const recipeStats = useMemo(() => {
    const stats = {
      totalRecipes: recipes.length,
      signatureRecipes: recipes.filter(r => r.is_signature_item).length,
      easyRecipes: recipes.filter(r => r.difficulty_level === 1).length,
      averageCost: recipes.length > 0 ? recipes.reduce((sum, r) => sum + (r.estimated_cost_per_unit || 0), 0) / recipes.length : 0,
      averageProfit: 0, // Will be calculated based on suggested selling price - cost
      categories: [...new Set(recipes.map(r => r.category).filter(Boolean))].length,
    };

    // Calculate average profit
    stats.averageProfit = recipes.length > 0 ?
      recipes.reduce((sum, r) => {
        const cost = r.estimated_cost_per_unit || 0;
        const price = r.suggested_selling_price || 0;
        return sum + (price - cost);
      }, 0) / recipes.length : 0;

    return stats;
  }, [recipes]);

  const stats = [
    {
      title: 'Total Recetas',
      value: recipeStats.totalRecipes,
      variant: 'default' as const,
      icon: ChefHat,
    },
    {
      title: 'Especiales',
      value: recipeStats.signatureRecipes,
      variant: 'warning' as const,
      icon: Star,
    },
    {
      title: 'Fáciles',
      value: recipeStats.easyRecipes,
      variant: 'success' as const,
      icon: Timer,
    },
    {
      title: 'Costo Promedio',
      value: formatters.currency(recipeStats.averageCost),
      variant: 'info' as const,
      icon: Euro,
    },
    {
      title: 'Margen Promedio',
      value: formatters.currency(recipeStats.averageProfit),
      variant: 'success' as const,
      icon: Euro,
    },
    {
      title: 'Categorías',
      value: recipeStats.categories,
      variant: 'info' as const,
      icon: Package,
    },
  ];

  // Handle creating a new recipe
  const handleCreateRecipe = async (recipeData: RecipeCreate) => {
    try {
      await createRecipeMutation.mutateAsync(recipeData);
      setShowCreateModal(false);
      console.log('Recipe created successfully');
    } catch (error) {
      console.error('Error creating recipe:', error);
      throw error;
    }
  };

  // Handle field changes in edit mode
  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number | boolean) => {
    if (!selectedRecipe) return;

    const fieldMap: Record<string, string> = {
      'Categoría': 'category',
      'Dificultad': 'difficulty_level',
      'Estado': 'status',
      'Rendimiento': 'yield_quantity',
      'Tiempo de preparación': 'prep_time_minutes',
      'Tiempo de cocción': 'cook_time_minutes',
      'Costo estimado por unidad': 'estimated_cost_per_unit',
      'Precio de venta sugerido': 'suggested_selling_price',
      'Margen objetivo': 'target_margin_percentage'
    };

    const sections = getModalSections();
    const field = sections[sectionIndex]?.fields[fieldIndex];
    const fieldKey = fieldMap[field?.label || ''];

    if (fieldKey) {
      setEditedRecipe(prev => ({
        ...prev,
        [fieldKey]: value
      }));
    }
  };

  // Handle saving edited recipe
  const handleSaveRecipe = async () => {
    if (!selectedRecipe || !Object.keys(editedRecipe).length) return;

    try {
      const updateData = {
        ...editedRecipe,
        // Convert time fields from formatted strings back to numbers if needed
        prep_time_minutes: typeof editedRecipe.prep_time_minutes === 'string'
          ? parseInt(editedRecipe.prep_time_minutes.toString())
          : editedRecipe.prep_time_minutes,
        cook_time_minutes: typeof editedRecipe.cook_time_minutes === 'string'
          ? parseInt(editedRecipe.cook_time_minutes.toString())
          : editedRecipe.cook_time_minutes,
        // Ensure yield_unit is properly typed
        yield_unit: editedRecipe.yield_unit ? editedRecipe.yield_unit as MeasurementUnit : undefined,
        // Convert difficulty level to number if needed
        difficulty_level: typeof editedRecipe.difficulty_level === 'string'
          ? parseInt(editedRecipe.difficulty_level.toString())
          : editedRecipe.difficulty_level,
      };

      await updateRecipeMutation.mutateAsync({
        id: selectedRecipe.id,
        data: updateData
      });

      setModalMode('view');
      setEditedRecipe({});
      console.log('Recipe updated successfully');
    } catch (error) {
      console.error('Error updating recipe:', error);
    }
  };

  // Get current value for field (edited value or original)
  const getFieldValue = (originalValue: any, fieldKey: string) => {
    return editedRecipe[fieldKey as keyof RecipeResponse] !== undefined
      ? editedRecipe[fieldKey as keyof RecipeResponse]
      : originalValue;
  };

  // Get modal sections with editable fields
  const getModalSections = () => {
    if (!selectedRecipe) return [];

    return [
      {
        title: 'Información Básica',
        icon: ChefHat,
        fields: [
          {
            label: 'Categoría',
            value: getFieldValue(selectedRecipe.category || 'Sin categoría', 'category'),
            type: modalMode === 'edit' ? 'select' : 'status',
            options: modalMode === 'edit' ? [
              { value: 'bread', label: 'Pan' },
              { value: 'pastry', label: 'Bollería' },
              { value: 'cake', label: 'Tarta' },
              { value: 'cookie', label: 'Galleta' },
              { value: 'other', label: 'Otro' }
            ] : undefined,
            editable: true
          },
          {
            label: 'Dificultad',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.difficulty_level, 'difficulty_level')
              : `Nivel ${getFieldValue(selectedRecipe.difficulty_level, 'difficulty_level')}`,
            type: modalMode === 'edit' ? 'select' : 'text',
            options: modalMode === 'edit' ? [
              { value: 1, label: '1 - Fácil' },
              { value: 2, label: '2 - Medio' },
              { value: 3, label: '3 - Difícil' },
              { value: 4, label: '4 - Muy Difícil' },
              { value: 5, label: '5 - Extremo' }
            ] : undefined,
            editable: true
          },
          {
            label: 'Estado',
            value: getFieldValue(selectedRecipe.status, 'status'),
            type: modalMode === 'edit' ? 'select' : 'text',
            options: modalMode === 'edit' ? [
              { value: 'draft', label: 'Borrador' },
              { value: 'active', label: 'Activo' },
              { value: 'archived', label: 'Archivado' }
            ] : undefined,
            highlight: selectedRecipe.status === 'active',
            editable: true
          },
          {
            label: 'Rendimiento',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.yield_quantity, 'yield_quantity')
              : `${getFieldValue(selectedRecipe.yield_quantity, 'yield_quantity')} ${selectedRecipe.yield_unit}`,
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          }
        ]
      },
      {
        title: 'Tiempos',
        icon: Clock,
        fields: [
          {
            label: 'Tiempo de preparación',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.prep_time_minutes || 0, 'prep_time_minutes')
              : formatTime(getFieldValue(selectedRecipe.prep_time_minutes || 0, 'prep_time_minutes')),
            type: modalMode === 'edit' ? 'number' : 'text',
            placeholder: modalMode === 'edit' ? 'minutos' : undefined,
            editable: modalMode === 'edit'
          },
          {
            label: 'Tiempo de cocción',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.cook_time_minutes || 0, 'cook_time_minutes')
              : formatTime(getFieldValue(selectedRecipe.cook_time_minutes || 0, 'cook_time_minutes')),
            type: modalMode === 'edit' ? 'number' : 'text',
            placeholder: modalMode === 'edit' ? 'minutos' : undefined,
            editable: modalMode === 'edit'
          },
          {
            label: 'Tiempo total',
            value: selectedRecipe.total_time_minutes ? formatTime(selectedRecipe.total_time_minutes) : 'No especificado',
            type: 'text',
            highlight: true,
            readonly: true
          }
        ]
      },
      {
        title: 'Análisis Financiero',
        icon: DollarSign,
        fields: [
          {
            label: 'Costo estimado por unidad',
            value: getFieldValue(selectedRecipe.estimated_cost_per_unit || 0, 'estimated_cost_per_unit'),
            type: modalMode === 'edit' ? 'number' : 'currency',
            editable: modalMode === 'edit'
          },
          {
            label: 'Precio de venta sugerido',
            value: getFieldValue(selectedRecipe.suggested_selling_price || 0, 'suggested_selling_price'),
            type: modalMode === 'edit' ? 'number' : 'currency',
            editable: modalMode === 'edit'
          },
          {
            label: 'Margen objetivo',
            value: getFieldValue(selectedRecipe.target_margin_percentage || 0, 'target_margin_percentage'),
            type: modalMode === 'edit' ? 'number' : 'percentage',
            highlight: true,
            editable: modalMode === 'edit'
          }
        ]
      },
      {
        title: 'Ingredientes',
        icon: Package,
        fields: [
          {
            label: 'Lista de ingredientes',
            value: selectedRecipe.ingredients?.map(ing => `${ing.quantity} ${ing.unit} - ${ing.ingredient_id}`) || ['No especificados'],
            type: 'list',
            span: 2,
            readonly: true // For now, ingredients editing can be complex, so we'll keep it read-only
          }
        ]
      }
    ];
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Gestión de Recetas"
        description="Administra y organiza todas las recetas de tu panadería"
        actions={[
          {
            id: "new",
            label: "Nueva Receta",
            variant: "primary" as const,
            icon: Plus,
            onClick: () => setShowCreateModal(true)
          }
        ]}
      />

      {/* Stats Grid */}
      <StatsGrid
        stats={stats}
        columns={3}
      />

      {/* Simplified Controls */}
      <Card className="p-4">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="flex-1">
            <Input
              placeholder="Buscar recetas por nombre, descripción o categoría..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full"
            />
          </div>
        </div>
      </Card>

      {/* Recipes Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {filteredRecipes.map((recipe) => {
          const statusConfig = getRecipeStatusConfig(recipe);
          const cost = recipe.estimated_cost_per_unit || 0;
          const price = recipe.suggested_selling_price || 0;
          const profitMargin = price > 0 ? Math.round(((price - cost) / price) * 100) : 0;
          const totalTime = formatTime((recipe.prep_time_minutes || 0) + (recipe.cook_time_minutes || 0));
          
          return (
            <StatusCard
              key={recipe.id}
              id={recipe.id}
              statusIndicator={statusConfig}
              title={recipe.name}
              subtitle={`${statusConfig.text} • ${statusConfig.difficultyLabel}${statusConfig.isHighlight ? ' ★' : ''}`}
              primaryValue={recipe.ingredients?.length || 0}
              primaryValueLabel="ingredientes"
              secondaryInfo={{
                label: 'Margen',
                value: `€${formatters.compact(price - cost)}`
              }}
              progress={{
                label: 'Margen de beneficio',
                percentage: profitMargin,
                color: profitMargin > 50 ? '#10b981' : profitMargin > 30 ? '#f59e0b' : '#ef4444'
              }}
              metadata={[
                `Tiempo: ${totalTime}`,
                `Rendimiento: ${recipe.yield_quantity} ${recipe.yield_unit}`,
                `${recipe.ingredients?.length || 0} ingredientes principales`
              ]}
              actions={[
                // Primary action - View recipe details
                {
                  label: 'Ver Detalles',
                  icon: Eye,
                  variant: 'primary',
                  priority: 'primary',
                  onClick: () => {
                    setSelectedRecipe(recipe);
                    setModalMode('view');
                    setShowForm(true);
                  }
                },
                // Secondary action - Edit recipe
                {
                  label: 'Editar',
                  icon: Edit,
                  priority: 'secondary',
                  onClick: () => {
                    setSelectedRecipe(recipe);
                    setModalMode('edit');
                    setShowForm(true);
                  }
                }
              ]}
            />
          );
        })}
      </div>

      {/* Empty State */}
      {filteredRecipes.length === 0 && (
        <div className="text-center py-12">
          <ChefHat className="mx-auto h-12 w-12 text-[var(--text-tertiary)] mb-4" />
          <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
            No se encontraron recetas
          </h3>
          <p className="text-[var(--text-secondary)] mb-4">
            Intenta ajustar la búsqueda o crear una nueva receta
          </p>
          <Button onClick={() => setShowForm(true)}>
            <Plus className="w-4 h-4 mr-2" />
            Nueva Receta
          </Button>
        </div>
      )}

      {/* Recipe Details Modal */}
      {showForm && selectedRecipe && (
        <StatusModal
          isOpen={showForm}
          onClose={() => {
            setShowForm(false);
            setSelectedRecipe(null);
            setModalMode('view');
            setEditedRecipe({});
          }}
          mode={modalMode}
          onModeChange={(newMode) => {
            setModalMode(newMode);
            if (newMode === 'view') {
              setEditedRecipe({});
            }
          }}
          title={selectedRecipe.name}
          subtitle={selectedRecipe.description || ''}
          statusIndicator={getRecipeStatusConfig(selectedRecipe)}
          size="xl"
          sections={getModalSections()}
          onFieldChange={handleFieldChange}
          showDefaultActions={true}
          onSave={handleSaveRecipe}
        />
      )}

      {/* Create Recipe Modal */}
      <CreateRecipeModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onCreateRecipe={handleCreateRecipe}
      />
    </div>
  );
};

export default RecipesPage;