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';

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<InitialStockEntryStepProps> = ({
  products: initialProducts,
  onUpdate,
  onComplete,
  onPrevious,
  initialData,
}) => {
  const { t } = useTranslation();
  const [products, setProducts] = useState<ProductWithStock[]>(() => {
    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 = () => {
    onComplete?.();
  };

  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 (
      <div className="max-w-4xl mx-auto p-4 md:p-6 space-y-4 md:space-y-6">
        <div className="text-center space-y-4">
          <div className="text-6xl">✓</div>
          <h2 className="text-xl md:text-2xl font-bold text-[var(--text-primary)]">
            {t('onboarding:stock.no_products_title', 'Stock Inicial')}
          </h2>
          <p className="text-[var(--text-secondary)]">
            {t('onboarding:stock.no_products_message', 'Podrás configurar los niveles de stock más tarde en la sección de inventario.')}
          </p>
          <Button onClick={handleContinue} variant="primary" rightIcon={<ArrowRight />}>
            {t('common:continue', 'Continuar')}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto p-4 md:p-6 space-y-4 md:space-y-6">
      {/* Header */}
      <div className="text-center space-y-2 md:space-y-3">
        <h1 className="text-xl md:text-2xl font-bold text-text-primary px-2">
          {t('onboarding:stock.title', 'Niveles de Stock Inicial')}
        </h1>
        <p className="text-sm md:text-base text-text-secondary max-w-2xl mx-auto px-4">
          {t(
            'onboarding:stock.subtitle',
            'Ingresa las cantidades actuales de cada producto. Esto permite que el sistema rastree el inventario desde hoy.'
          )}
        </p>
      </div>

      {/* Info Banner */}
      <Card className="bg-blue-50 border-blue-200">
        <div className="p-4 flex items-start gap-3">
          <AlertCircle className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-blue-900">
            <p className="font-medium mb-1">
              {t('onboarding:stock.info_title', '¿Por qué es importante?')}
            </p>
            <p className="text-blue-700">
              {t(
                'onboarding:stock.info_text',
                'Sin niveles de stock iniciales, el sistema no puede alertarte sobre stock bajo, planificar producción o calcular costos correctamente. Tómate un momento para ingresar tus cantidades actuales.'
              )}
            </p>
          </div>
        </div>
      </Card>

      {/* Progress */}
      <div className="space-y-2">
        <div className="flex items-center justify-between text-sm">
          <span className="text-text-secondary">
            {t('onboarding:stock.progress', 'Progreso de captura')}
          </span>
          <span className="font-medium text-text-primary">
            {productsWithStock.length} / {products.length}
          </span>
        </div>
        <div className="w-full bg-gray-200 rounded-full h-2">
          <div
            className="bg-primary-500 h-2 rounded-full transition-all duration-300"
            style={{ width: `${completionPercentage}%` }}
          />
        </div>
      </div>

      {/* Quick Actions */}
      <div className="flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2">
        <Button onClick={handleSetAllToZero} variant="outline" size="sm" className="w-full sm:w-auto">
          {t('onboarding:stock.set_all_zero', 'Establecer todo a 0')}
        </Button>
        <Button onClick={handleSkipForNow} variant="ghost" size="sm" className="w-full sm:w-auto">
          {t('onboarding:stock.skip_for_now', 'Omitir por ahora (se establecerá a 0)')}
        </Button>
      </div>

      {/* Ingredients Section */}
      {ingredients.length > 0 && (
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
              <Salad className="w-4 h-4 text-green-600" />
            </div>
            <h3 className="font-semibold text-text-primary">
              {t('onboarding:stock.ingredients', 'Ingredientes')} ({ingredients.length})
            </h3>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {ingredients.map(product => {
              const hasStock = product.initialStock !== undefined;
              return (
                <Card key={product.id} className={hasStock ? 'bg-green-50 border-green-200' : ''}>
                  <div className="p-3">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1">
                        <div className="font-medium text-text-primary flex items-center gap-2">
                          {product.name}
                          {hasStock && <CheckCircle className="w-4 h-4 text-green-600" />}
                        </div>
                        {product.category && (
                          <div className="text-xs text-text-secondary">{product.category}</div>
                        )}
                      </div>
                      <div className="flex items-center gap-2">
                        <Input
                          type="number"
                          value={product.initialStock ?? ''}
                          onChange={(e) => handleStockChange(product.id, e.target.value)}
                          placeholder="0"
                          min="0"
                          step="0.01"
                          className="w-20 sm:w-24 text-right min-h-[44px]"
                        />
                        <span className="text-sm text-text-secondary whitespace-nowrap">
                          {product.unit || 'kg'}
                        </span>
                      </div>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
      )}

      {/* Finished Products Section */}
      {finishedProducts.length > 0 && (
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
              <Package className="w-4 h-4 text-blue-600" />
            </div>
            <h3 className="font-semibold text-text-primary">
              {t('onboarding:stock.finished_products', 'Productos Terminados')} ({finishedProducts.length})
            </h3>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {finishedProducts.map(product => {
              const hasStock = product.initialStock !== undefined;
              return (
                <Card key={product.id} className={hasStock ? 'bg-blue-50 border-blue-200' : ''}>
                  <div className="p-3">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1">
                        <div className="font-medium text-text-primary flex items-center gap-2">
                          {product.name}
                          {hasStock && <CheckCircle className="w-4 h-4 text-blue-600" />}
                        </div>
                        {product.category && (
                          <div className="text-xs text-text-secondary">{product.category}</div>
                        )}
                      </div>
                      <div className="flex items-center gap-2">
                        <Input
                          type="number"
                          value={product.initialStock ?? ''}
                          onChange={(e) => handleStockChange(product.id, e.target.value)}
                          placeholder="0"
                          min="0"
                          step="1"
                          className="w-24 text-right"
                        />
                        <span className="text-sm text-text-secondary whitespace-nowrap">
                          {product.unit || t('common:units', 'unidades')}
                        </span>
                      </div>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
      )}

      {/* Warning for incomplete */}
      {!allCompleted && (
        <Card className="bg-amber-50 border-amber-200">
          <div className="p-4 flex items-start gap-3">
            <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
            <div className="text-sm text-amber-900">
              <p className="font-medium">
                {t('onboarding:stock.incomplete_warning', 'Faltan {count} productos por completar', {
                  count: productsWithoutStock.length,
                })}
              </p>
              <p className="text-amber-700 mt-1">
                {t(
                  'onboarding:stock.incomplete_help',
                  'Puedes continuar, pero recomendamos ingresar todas las cantidades para un mejor control de inventario.'
                )}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Footer Actions */}
      <div className="flex items-center justify-between pt-6 border-t border-border-primary">
        <Button onClick={onPrevious} variant="ghost" leftIcon={<ArrowLeft />}>
          {t('common:previous', 'Anterior')}
        </Button>

        <Button onClick={handleContinue} variant="primary" rightIcon={<ArrowRight />}>
          {allCompleted
            ? t('onboarding:stock.complete', 'Completar Configuración')
            : t('onboarding:stock.continue_anyway', 'Continuar de todos modos')}
        </Button>
      </div>
    </div>
  );
};

export default InitialStockEntryStep;
