import React, { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Package, Salad, AlertCircle, ArrowRight, ArrowLeft, CheckCircle } from 'lucide-react'; import Button from '../../../ui/Button/Button'; import Card from '../../../ui/Card/Card'; import Input from '../../../ui/Input/Input'; import { useCurrentTenant } from '../../../../stores/tenant.store'; import { useAddStock } from '../../../../api/hooks/inventory'; import InfoCard from '../../../ui/InfoCard'; export interface ProductWithStock { id: string; name: string; type: 'ingredient' | 'finished_product'; category?: string; unit?: string; initialStock?: number; } export interface InitialStockEntryStepProps { products?: ProductWithStock[]; // Made optional - will use empty array if not provided onUpdate?: (data: { productsWithStock: ProductWithStock[] }) => void; onComplete?: () => void; onPrevious?: () => void; initialData?: { productsWithStock?: ProductWithStock[]; }; } export const InitialStockEntryStep: React.FC = ({ products: initialProducts, onUpdate, onComplete, onPrevious, initialData, }) => { const { t } = useTranslation(); const currentTenant = useCurrentTenant(); const tenantId = currentTenant?.id || ''; const addStockMutation = useAddStock(); const [isSaving, setIsSaving] = useState(false); const [products, setProducts] = useState(() => { if (initialData?.productsWithStock) { return initialData.productsWithStock; } // Handle case where initialProducts is undefined (shouldn't happen, but defensive) if (!initialProducts || initialProducts.length === 0) { return []; } return initialProducts.map(p => ({ ...p, initialStock: p.initialStock ?? undefined, })); }); const ingredients = products.filter(p => p.type === 'ingredient'); const finishedProducts = products.filter(p => p.type === 'finished_product'); const handleStockChange = (productId: string, value: string) => { const numValue = value === '' ? undefined : parseFloat(value); const updatedProducts = products.map(p => p.id === productId ? { ...p, initialStock: numValue } : p ); setProducts(updatedProducts); onUpdate?.({ productsWithStock: updatedProducts }); }; const handleSetAllToZero = () => { const updatedProducts = products.map(p => ({ ...p, initialStock: 0 })); setProducts(updatedProducts); onUpdate?.({ productsWithStock: updatedProducts }); }; const handleSkipForNow = () => { // Set all undefined values to 0 const updatedProducts = products.map(p => ({ ...p, initialStock: p.initialStock ?? 0, })); setProducts(updatedProducts); onUpdate?.({ productsWithStock: updatedProducts }); onComplete?.(); }; const handleContinue = async () => { setIsSaving(true); try { // Create stock entries for products with initial stock > 0 const stockEntries = products.filter(p => p.initialStock && p.initialStock > 0); if (stockEntries.length > 0) { // Create stock entries in parallel const stockPromises = stockEntries.map(product => addStockMutation.mutateAsync({ tenantId, stockData: { ingredient_id: product.id, current_quantity: product.initialStock!, // The actual stock quantity unit_cost: 0, // Default cost, can be updated later } }) ); await Promise.all(stockPromises); console.log(`✅ Created ${stockEntries.length} stock entries successfully`); } onComplete?.(); } catch (error) { console.error('Error creating stock entries:', error); alert(t('onboarding:stock.error_creating_stock', 'Error al crear los niveles de stock. Por favor, inténtalo de nuevo.')); } finally { setIsSaving(false); } }; const productsWithStock = products.filter(p => p.initialStock !== undefined && p.initialStock >= 0); const productsWithoutStock = products.filter(p => p.initialStock === undefined); const completionPercentage = products.length > 0 ? (productsWithStock.length / products.length) * 100 : 100; const allCompleted = productsWithoutStock.length === 0; // If no products, show a skip message if (products.length === 0) { return (

{t('onboarding:stock.no_products_title', 'Stock Inicial')}

{t('onboarding:stock.no_products_message', 'Podrás configurar los niveles de stock más tarde en la sección de inventario.')}

); } return (
{/* Why This Matters */} {/* Progress */}
{t('onboarding:stock.progress', 'Progreso de captura')} {productsWithStock.length} / {products.length}
{/* Quick Actions */}
{/* Ingredients Section */} {ingredients.length > 0 && (

{t('onboarding:stock.ingredients', 'Ingredientes')} ({ingredients.length})

{ingredients.map(product => { const hasStock = product.initialStock !== undefined; return (
{product.name} {hasStock && }
{product.category && (
{product.category}
)}
handleStockChange(product.id, e.target.value)} placeholder="0" min="0" step="0.01" className="w-20 sm:w-24 text-right min-h-[44px]" /> {product.unit || 'kg'}
); })}
)} {/* Finished Products Section */} {finishedProducts.length > 0 && (

{t('onboarding:stock.finished_products', 'Productos Terminados')} ({finishedProducts.length})

{finishedProducts.map(product => { const hasStock = product.initialStock !== undefined; return (
{product.name} {hasStock && }
{product.category && (
{product.category}
)}
handleStockChange(product.id, e.target.value)} placeholder="0" min="0" step="1" className="w-24 text-right" /> {product.unit || t('common:units', 'unidades')}
); })}
)} {/* Warning for incomplete */} {!allCompleted && ( )} {/* Footer Actions */}
); }; export default InitialStockEntryStep;