import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Package, Salad, ArrowRight, ArrowLeft, Info } from 'lucide-react';
import Button from '../../../ui/Button/Button';
import Card from '../../../ui/Card/Card';

export interface Product {
  id: string;
  name: string;
  category?: string;
  confidence?: number;
  type?: 'ingredient' | 'finished_product' | null;
  suggestedType?: 'ingredient' | 'finished_product';
}

export interface ProductCategorizationStepProps {
  products: Product[];
  onUpdate?: (data: { categorizedProducts: Product[] }) => void;
  onComplete?: () => void;
  onPrevious?: () => void;
  initialData?: {
    categorizedProducts?: Product[];
  };
}

export const ProductCategorizationStep: React.FC<ProductCategorizationStepProps> = ({
  products: initialProducts,
  onUpdate,
  onComplete,
  onPrevious,
  initialData,
}) => {
  const { t } = useTranslation();
  const [products, setProducts] = useState<Product[]>(() => {
    if (initialData?.categorizedProducts) {
      return initialData.categorizedProducts;
    }
    return initialProducts.map(p => ({
      ...p,
      type: p.suggestedType || null,
    }));
  });

  const [draggedProduct, setDraggedProduct] = useState<Product | null>(null);

  const uncategorizedProducts = products.filter(p => !p.type);
  const ingredients = products.filter(p => p.type === 'ingredient');
  const finishedProducts = products.filter(p => p.type === 'finished_product');

  const handleDragStart = (product: Product) => {
    setDraggedProduct(product);
  };

  const handleDragEnd = () => {
    setDraggedProduct(null);
  };

  const handleDrop = (type: 'ingredient' | 'finished_product') => {
    if (!draggedProduct) return;

    const updatedProducts = products.map(p =>
      p.id === draggedProduct.id ? { ...p, type } : p
    );

    setProducts(updatedProducts);
    onUpdate?.({ categorizedProducts: updatedProducts });
    setDraggedProduct(null);
  };

  const handleMoveProduct = (productId: string, type: 'ingredient' | 'finished_product' | null) => {
    const updatedProducts = products.map(p =>
      p.id === productId ? { ...p, type } : p
    );

    setProducts(updatedProducts);
    onUpdate?.({ categorizedProducts: updatedProducts });
  };

  const handleAcceptAllSuggestions = () => {
    const updatedProducts = products.map(p => ({
      ...p,
      type: p.suggestedType || p.type,
    }));

    setProducts(updatedProducts);
    onUpdate?.({ categorizedProducts: updatedProducts });
  };

  const handleContinue = () => {
    onComplete?.();
  };

  const allCategorized = uncategorizedProducts.length === 0;
  const categorizationProgress = ((products.length - uncategorizedProducts.length) / products.length) * 100;

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="text-center space-y-3">
        <h1 className="text-2xl font-bold text-text-primary">
          {t('onboarding:categorization.title', 'Categoriza tus Productos')}
        </h1>
        <p className="text-text-secondary max-w-2xl mx-auto">
          {t(
            'onboarding:categorization.subtitle',
            'Ayúdanos a entender qué son ingredientes (para usar en recetas) y qué son productos terminados (para vender)'
          )}
        </p>
      </div>

      {/* Info Banner */}
      <Card className="bg-blue-50 border-blue-200">
        <div className="p-4 flex items-start gap-3">
          <Info 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:categorization.info_title', '¿Por qué es importante?')}
            </p>
            <p className="text-blue-700">
              {t(
                'onboarding:categorization.info_text',
                'Los ingredientes se usan en recetas para crear productos. Los productos terminados se venden directamente. Esta clasificación permite calcular costos y planificar producción correctamente.'
              )}
            </p>
          </div>
        </div>
      </Card>

      {/* Progress Bar */}
      <div className="space-y-2">
        <div className="flex items-center justify-between text-sm">
          <span className="text-text-secondary">
            {t('onboarding:categorization.progress', 'Progreso de categorización')}
          </span>
          <span className="font-medium text-text-primary">
            {products.length - uncategorizedProducts.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: `${categorizationProgress}%` }}
          />
        </div>
      </div>

      {/* Quick Actions */}
      {uncategorizedProducts.length > 0 && products.some(p => p.suggestedType) && (
        <div className="flex justify-end">
          <Button onClick={handleAcceptAllSuggestions} variant="outline" size="sm">
            {t('onboarding:categorization.accept_all_suggestions', '⚡ Aceptar todas las sugerencias de IA')}
          </Button>
        </div>
      )}

      {/* Categorization Areas */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Uncategorized */}
        {uncategorizedProducts.length > 0 && (
          <Card className="bg-gray-50">
            <div className="p-4 space-y-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-gray-200 rounded-lg flex items-center justify-center">
                  <span className="text-lg">📦</span>
                </div>
                <div>
                  <h3 className="font-semibold text-text-primary">
                    {t('onboarding:categorization.uncategorized', 'Sin Categorizar')}
                  </h3>
                  <p className="text-xs text-text-secondary">
                    {uncategorizedProducts.length} {t('common:items', 'items')}
                  </p>
                </div>
              </div>

              <div className="space-y-2 max-h-96 overflow-y-auto">
                {uncategorizedProducts.map(product => (
                  <div
                    key={product.id}
                    draggable
                    onDragStart={() => handleDragStart(product)}
                    onDragEnd={handleDragEnd}
                    className="p-3 bg-white border border-gray-200 rounded-lg cursor-move hover:shadow-md transition-all"
                  >
                    <div className="font-medium text-text-primary">{product.name}</div>
                    {product.category && (
                      <div className="text-xs text-text-secondary mt-1">{product.category}</div>
                    )}
                    {product.suggestedType && (
                      <div className="text-xs text-primary-600 mt-1 flex items-center gap-1">
                        <span>⚡</span>
                        {t(
                          `onboarding:categorization.suggested_${product.suggestedType}`,
                          product.suggestedType === 'ingredient' ? 'Sugerido: Ingrediente' : 'Sugerido: Producto'
                        )}
                      </div>
                    )}
                    <div className="flex gap-2 mt-2">
                      <button
                        onClick={() => handleMoveProduct(product.id, 'ingredient')}
                        className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors"
                      >
                        → {t('onboarding:categorization.ingredient', 'Ingrediente')}
                      </button>
                      <button
                        onClick={() => handleMoveProduct(product.id, 'finished_product')}
                        className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
                      >
                        → {t('onboarding:categorization.finished_product', 'Producto')}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </Card>
        )}

        {/* Ingredients */}
        <Card
          className={`${draggedProduct ? 'ring-2 ring-green-300' : ''} transition-all`}
          onDragOver={(e) => e.preventDefault()}
          onDrop={() => handleDrop('ingredient')}
        >
          <div className="p-4 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>
              <div>
                <h3 className="font-semibold text-text-primary">
                  {t('onboarding:categorization.ingredients_title', 'Ingredientes')}
                </h3>
                <p className="text-xs text-text-secondary">
                  {ingredients.length} {t('common:items', 'items')}
                </p>
              </div>
            </div>

            <p className="text-xs text-text-secondary">
              {t('onboarding:categorization.ingredients_help', 'Para usar en recetas')}
            </p>

            <div className="space-y-2 max-h-96 overflow-y-auto">
              {ingredients.length === 0 && (
                <div className="p-4 border-2 border-dashed border-gray-300 rounded-lg text-center text-sm text-text-secondary">
                  {t('onboarding:categorization.drag_here', 'Arrastra productos aquí')}
                </div>
              )}
              {ingredients.map(product => (
                <div
                  key={product.id}
                  className="p-3 bg-green-50 border border-green-200 rounded-lg"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="font-medium text-text-primary">{product.name}</div>
                      {product.category && (
                        <div className="text-xs text-text-secondary mt-1">{product.category}</div>
                      )}
                    </div>
                    <button
                      onClick={() => handleMoveProduct(product.id, null)}
                      className="text-gray-400 hover:text-gray-600 transition-colors"
                      title={t('common:remove', 'Quitar')}
                    >
                      <ArrowLeft className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Card>

        {/* Finished Products */}
        <Card
          className={`${draggedProduct ? 'ring-2 ring-blue-300' : ''} transition-all`}
          onDragOver={(e) => e.preventDefault()}
          onDrop={() => handleDrop('finished_product')}
        >
          <div className="p-4 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>
              <div>
                <h3 className="font-semibold text-text-primary">
                  {t('onboarding:categorization.finished_products_title', 'Productos Terminados')}
                </h3>
                <p className="text-xs text-text-secondary">
                  {finishedProducts.length} {t('common:items', 'items')}
                </p>
              </div>
            </div>

            <p className="text-xs text-text-secondary">
              {t('onboarding:categorization.finished_products_help', 'Para vender directamente')}
            </p>

            <div className="space-y-2 max-h-96 overflow-y-auto">
              {finishedProducts.length === 0 && (
                <div className="p-4 border-2 border-dashed border-gray-300 rounded-lg text-center text-sm text-text-secondary">
                  {t('onboarding:categorization.drag_here', 'Arrastra productos aquí')}
                </div>
              )}
              {finishedProducts.map(product => (
                <div
                  key={product.id}
                  className="p-3 bg-blue-50 border border-blue-200 rounded-lg"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="font-medium text-text-primary">{product.name}</div>
                      {product.category && (
                        <div className="text-xs text-text-secondary mt-1">{product.category}</div>
                      )}
                    </div>
                    <button
                      onClick={() => handleMoveProduct(product.id, null)}
                      className="text-gray-400 hover:text-gray-600 transition-colors"
                      title={t('common:remove', 'Quitar')}
                    >
                      <ArrowLeft className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>

      {/* 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>

        <div className="text-center">
          {!allCategorized && (
            <p className="text-sm text-amber-600">
              {t(
                'onboarding:categorization.incomplete_warning',
                '⚠️ Categoriza todos los productos para continuar'
              )}
            </p>
          )}
        </div>

        <Button
          onClick={handleContinue}
          disabled={!allCategorized}
          variant="primary"
          rightIcon={<ArrowRight />}
        >
          {t('common:continue', 'Continuar')}
        </Button>
      </div>
    </div>
  );
};

export default ProductCategorizationStep;
