import React, { useState } from 'react';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { Package, Leaf, Cookie, CheckCircle2 } from 'lucide-react';

interface WizardDataProps extends WizardStepProps {
  data: Record<string, any>;
  onDataChange: (data: Record<string, any>) => void;
}

// Step 1: Type Selection
const TypeSelectionStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
  const [selectedType, setSelectedType] = useState<'ingredient' | 'finished_product'>(
    data.inventoryType || 'ingredient'
  );

  const handleContinue = () => {
    onDataChange({ ...data, inventoryType: selectedType });
    onNext();
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          ¿Qué tipo de inventario agregarás?
        </h3>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <button
          onClick={() => setSelectedType('ingredient')}
          className={`
            p-6 rounded-xl border-2 transition-all duration-200
            hover:shadow-lg hover:-translate-y-0.5
            ${
              selectedType === 'ingredient'
                ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/10 shadow-md ring-2 ring-[var(--color-primary)]/20'
                : 'border-[var(--border-secondary)] hover:border-[var(--color-primary)]/50'
            }
          `}
        >
          <Leaf className={`w-10 h-10 mx-auto mb-4 transition-colors ${
            selectedType === 'ingredient' ? 'text-[var(--color-primary)]' : 'text-[var(--text-tertiary)]'
          }`} />
          <h4 className={`font-semibold mb-3 transition-colors ${
            selectedType === 'ingredient' ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'
          }`}>
            Ingrediente
          </h4>
          <p className="text-sm text-[var(--text-secondary)] leading-relaxed">
            Materias primas usadas en recetas
          </p>
          <p className="text-xs text-[var(--text-tertiary)] mt-3 leading-relaxed">
            Ej: Harina, azúcar, huevos, mantequilla
          </p>
        </button>

        <button
          onClick={() => setSelectedType('finished_product')}
          className={`
            p-6 rounded-xl border-2 transition-all duration-200
            hover:shadow-lg hover:-translate-y-0.5
            ${
              selectedType === 'finished_product'
                ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/10 shadow-md ring-2 ring-[var(--color-primary)]/20'
                : 'border-[var(--border-secondary)] hover:border-[var(--color-primary)]/50'
            }
          `}
        >
          <Cookie className={`w-10 h-10 mx-auto mb-4 transition-colors ${
            selectedType === 'finished_product' ? 'text-[var(--color-primary)]' : 'text-[var(--text-tertiary)]'
          }`} />
          <h4 className={`font-semibold mb-3 transition-colors ${
            selectedType === 'finished_product' ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'
          }`}>
            Producto Terminado
          </h4>
          <p className="text-sm text-[var(--text-secondary)] leading-relaxed">
            Productos listos para venta
          </p>
          <p className="text-xs text-[var(--text-tertiary)] mt-3 leading-relaxed">
            Ej: Baguettes, croissants, pasteles
          </p>
        </button>
      </div>

      <div className="flex justify-end">
        <button
          onClick={handleContinue}
          className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 transition-colors"
        >
          Continuar
        </button>
      </div>
    </div>
  );
};

// Step 2: Core Details
const CoreDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
  const isIngredient = data.inventoryType === 'ingredient';

  const [formData, setFormData] = useState({
    name: data.name || '',
    category: data.category || '',
    unit: data.unit || '',
    storage: data.storage || 'dry',
    reorderPoint: data.reorderPoint || '',
    shelfLife: data.shelfLife || '',
  });

  const handleSubmit = () => {
    onDataChange({ ...data, ...formData });
    onNext();
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          Detalles del {isIngredient ? 'Ingrediente' : 'Producto'}
        </h3>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            Nombre *
          </label>
          <input
            type="text"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            placeholder={isIngredient ? "Ej: Harina de trigo" : "Ej: Baguette tradicional"}
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            Categoría *
          </label>
          <select
            value={formData.category}
            onChange={(e) => setFormData({ ...formData, category: e.target.value })}
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          >
            <option value="">Seleccionar...</option>
            {isIngredient ? (
              <>
                <option value="flour">Harinas</option>
                <option value="dairy">Lácteos</option>
                <option value="eggs">Huevos</option>
                <option value="fats">Grasas</option>
                <option value="sweeteners">Endulzantes</option>
                <option value="additives">Aditivos</option>
              </>
            ) : (
              <>
                <option value="bread">Pan</option>
                <option value="pastry">Pastelería</option>
                <option value="cake">Repostería</option>
                <option value="cookies">Galletas</option>
              </>
            )}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            Unidad de Medida *
          </label>
          <select
            value={formData.unit}
            onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          >
            <option value="">Seleccionar...</option>
            <option value="kg">Kilogramos (kg)</option>
            <option value="l">Litros (L)</option>
            <option value="units">Unidades</option>
            <option value="g">Gramos (g)</option>
            <option value="ml">Mililitros (ml)</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            Almacenamiento
          </label>
          <select
            value={formData.storage}
            onChange={(e) => setFormData({ ...formData, storage: e.target.value })}
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          >
            <option value="dry">Seco</option>
            <option value="refrigerated">Refrigerado</option>
            <option value="frozen">Congelado</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            Punto de Reorden
          </label>
          <input
            type="number"
            value={formData.reorderPoint}
            onChange={(e) => setFormData({ ...formData, reorderPoint: e.target.value })}
            placeholder="Cantidad mínima"
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            min="0"
          />
        </div>
      </div>

      <div className="flex justify-end">
        <button
          onClick={handleSubmit}
          disabled={!formData.name || !formData.category || !formData.unit}
          className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          Continuar
        </button>
      </div>
    </div>
  );
};

// Step 3: Initial Lot (Optional)
const InitialLotStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
  const [addLot, setAddLot] = useState(false);
  const [lotData, setLotData] = useState({
    quantity: '',
    batchNumber: '',
    expiryDate: '',
    costPerUnit: '',
  });

  const handleComplete = () => {
    if (addLot) {
      onDataChange({ ...data, initialLot: lotData });
    }
    // Here you would save to API
    console.log('Saving inventory:', data);
    onComplete();
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          Inventario Inicial (Opcional)
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          Agrega un lote inicial si ya tienes stock
        </p>
      </div>

      <div className="text-center">
        <button
          onClick={() => setAddLot(!addLot)}
          className={`px-6 py-3 rounded-lg border-2 transition-all ${
            addLot
              ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/5 text-[var(--color-primary)]'
              : 'border-[var(--border-secondary)] text-[var(--text-secondary)]'
          }`}
        >
          {addLot ? '✓ Agregar lote inicial' : '+ Agregar lote inicial'}
        </button>
      </div>

      {addLot && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]/30">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Cantidad *
            </label>
            <input
              type="number"
              value={lotData.quantity}
              onChange={(e) => setLotData({ ...lotData, quantity: e.target.value })}
              placeholder="100"
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
              min="0"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Número de Lote
            </label>
            <input
              type="text"
              value={lotData.batchNumber}
              onChange={(e) => setLotData({ ...lotData, batchNumber: e.target.value })}
              placeholder="LOT-2025-001"
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Fecha de Caducidad
            </label>
            <input
              type="date"
              value={lotData.expiryDate}
              onChange={(e) => setLotData({ ...lotData, expiryDate: e.target.value })}
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Costo por Unidad (€)
            </label>
            <input
              type="number"
              value={lotData.costPerUnit}
              onChange={(e) => setLotData({ ...lotData, costPerUnit: e.target.value })}
              placeholder="1.50"
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
              min="0"
              step="0.01"
            />
          </div>
        </div>
      )}

      <div className="flex justify-end gap-3 pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={handleComplete}
          className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-semibold inline-flex items-center gap-2"
        >
          <CheckCircle2 className="w-5 h-5" />
          Finalizar
        </button>
      </div>
    </div>
  );
};

export const InventoryWizardSteps = (
  data: Record<string, any>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => [
  {
    id: 'type-selection',
    title: 'Tipo',
    description: 'Ingrediente o producto terminado',
    component: (props) => <TypeSelectionStep {...props} data={data} onDataChange={setData} />,
  },
  {
    id: 'core-details',
    title: 'Detalles',
    description: 'Información básica',
    component: (props) => <CoreDetailsStep {...props} data={data} onDataChange={setData} />,
  },
  {
    id: 'initial-lot',
    title: 'Lote Inicial',
    description: 'Inventario de arranque (opcional)',
    component: (props) => <InitialLotStep {...props} data={data} onDataChange={setData} />,
    isOptional: true,
  },
];
