import React, { useState } from 'react';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { Building2, Package, Euro, CheckCircle2, Phone, Mail } from 'lucide-react';

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

// Step 1: Supplier Information
const SupplierInfoStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
  const [supplierData, setSupplierData] = useState({
    name: data.name || '',
    contactPerson: data.contactPerson || '',
    phone: data.phone || '',
    email: data.email || '',
    address: data.address || '',
    paymentTerms: data.paymentTerms || 'net30',
    notes: data.notes || '',
  });

  const handleContinue = () => {
    onDataChange({ ...data, ...supplierData });
    onNext();
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Building2 className="w-12 h-12 mx-auto mb-3 text-[var(--color-primary)]" />
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          Información del Proveedor
        </h3>
      </div>

      <div className="space-y-4">
        <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 del Proveedor *
            </label>
            <input
              type="text"
              value={supplierData.name}
              onChange={(e) => setSupplierData({ ...supplierData, name: e.target.value })}
              placeholder="Ej: Harinas Premium S.L."
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Persona de Contacto
            </label>
            <input
              type="text"
              value={supplierData.contactPerson}
              onChange={(e) => setSupplierData({ ...supplierData, contactPerson: e.target.value })}
              placeholder="Nombre del contacto"
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              <Phone className="w-3.5 h-3.5 inline mr-1" />
              Teléfono *
            </label>
            <input
              type="tel"
              value={supplierData.phone}
              onChange={(e) => setSupplierData({ ...supplierData, phone: e.target.value })}
              placeholder="+34 123 456 789"
              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)]"
            />
          </div>

          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              <Mail className="w-3.5 h-3.5 inline mr-1" />
              Email
            </label>
            <input
              type="email"
              value={supplierData.email}
              onChange={(e) => setSupplierData({ ...supplierData, email: e.target.value })}
              placeholder="pedidos@proveedor.com"
              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)]"
            />
          </div>

          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Dirección
            </label>
            <textarea
              value={supplierData.address}
              onChange={(e) => setSupplierData({ ...supplierData, address: e.target.value })}
              placeholder="Calle, ciudad, código postal..."
              rows={2}
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Condiciones de Pago
            </label>
            <select
              value={supplierData.paymentTerms}
              onChange={(e) => setSupplierData({ ...supplierData, paymentTerms: 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)]"
            >
              <option value="immediate">Pago Inmediato</option>
              <option value="net15">Net 15 días</option>
              <option value="net30">Net 30 días</option>
              <option value="net60">Net 60 días</option>
            </select>
          </div>

          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Notas
            </label>
            <textarea
              value={supplierData.notes}
              onChange={(e) => setSupplierData({ ...supplierData, notes: e.target.value })}
              placeholder="Horarios de pedido, condiciones especiales..."
              rows={2}
              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)]"
            />
          </div>
        </div>
      </div>

      <div className="flex justify-end pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={handleContinue}
          disabled={!supplierData.name || !supplierData.phone}
          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 2: Products & Pricing
const ProductsPricingStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
  const [products, setProducts] = useState(data.products || []);

  // Mock ingredient list - replace with actual API call
  const mockIngredients = [
    { id: 1, name: 'Harina de Trigo', unit: 'kg' },
    { id: 2, name: 'Mantequilla', unit: 'kg' },
    { id: 3, name: 'Azúcar', unit: 'kg' },
    { id: 4, name: 'Levadura', unit: 'kg' },
  ];

  const handleAddProduct = () => {
    setProducts([
      ...products,
      { id: Date.now(), ingredientId: '', price: 0, minimumOrder: 1 },
    ]);
  };

  const handleUpdateProduct = (index: number, field: string, value: any) => {
    const updated = products.map((item: any, i: number) => {
      if (i === index) {
        return { ...item, [field]: value };
      }
      return item;
    });
    setProducts(updated);
  };

  const handleRemoveProduct = (index: number) => {
    setProducts(products.filter((_: any, i: number) => i !== index));
  };

  const handleConfirm = () => {
    onDataChange({ ...data, products });
    console.log('Saving supplier:', { ...data, products });
    onComplete();
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Package className="w-12 h-12 mx-auto mb-3 text-[var(--color-primary)]" />
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          Productos y Precios
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {data.name}
        </p>
      </div>

      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <label className="block text-sm font-medium text-[var(--text-secondary)]">
            Ingredientes que Suministra
          </label>
          <button
            onClick={handleAddProduct}
            className="px-3 py-1.5 text-sm bg-[var(--color-primary)] text-white rounded-md hover:bg-[var(--color-primary)]/90 transition-colors"
          >
            + Agregar Producto
          </button>
        </div>

        {products.length === 0 ? (
          <div className="text-center py-12 border-2 border-dashed border-[var(--border-secondary)] rounded-lg">
            <p className="text-[var(--text-tertiary)]">No hay productos agregados</p>
          </div>
        ) : (
          <div className="space-y-2">
            {products.map((product: any, index: number) => (
              <div
                key={product.id}
                className="p-3 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]/30"
              >
                <div className="grid grid-cols-12 gap-2 items-center">
                  <div className="col-span-12 md:col-span-5">
                    <select
                      value={product.ingredientId}
                      onChange={(e) => handleUpdateProduct(index, 'ingredientId', e.target.value)}
                      className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--color-primary)]"
                    >
                      <option value="">Seleccionar ingrediente...</option>
                      {mockIngredients.map((ing) => (
                        <option key={ing.id} value={ing.id}>
                          {ing.name} ({ing.unit})
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="col-span-5 md:col-span-3">
                    <input
                      type="number"
                      value={product.price}
                      onChange={(e) => handleUpdateProduct(index, 'price', parseFloat(e.target.value) || 0)}
                      placeholder="Precio/unidad"
                      className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--color-primary)]"
                      min="0"
                      step="0.01"
                    />
                  </div>
                  <div className="col-span-6 md:col-span-3">
                    <input
                      type="number"
                      value={product.minimumOrder}
                      onChange={(e) => handleUpdateProduct(index, 'minimumOrder', parseFloat(e.target.value) || 0)}
                      placeholder="Pedido mín."
                      className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--color-primary)]"
                      min="1"
                    />
                  </div>
                  <div className="col-span-1">
                    <button
                      onClick={() => handleRemoveProduct(index)}
                      className="p-1 text-red-500 hover:text-red-700"
                    >
                      ✕
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="flex justify-end gap-3 pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={handleConfirm}
          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" />
          Crear Proveedor
        </button>
      </div>
    </div>
  );
};

export const SupplierWizardSteps = (
  data: Record<string, any>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => [
  {
    id: 'supplier-info',
    title: 'Información del Proveedor',
    description: 'Datos de contacto y términos',
    component: (props) => <SupplierInfoStep {...props} data={data} onDataChange={setData} />,
  },
  {
    id: 'supplier-products',
    title: 'Productos y Precios',
    description: 'Ingredientes que suministra',
    component: (props) => <ProductsPricingStep {...props} data={data} onDataChange={setData} />,
    isOptional: true,
  },
];
