import React, { useState } from 'react';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import {
  Users,
  Mail,
  Phone,
  MapPin,
  Building,
  CreditCard,
  Calendar,
  AlertTriangle,
  CheckCircle2,
} from 'lucide-react';

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

// Step 1: Customer Details
const CustomerDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
  const [customerData, setCustomerData] = useState({
    name: data.name || '',
    customerType: data.customerType || 'retail',
    contactPerson: data.contactPerson || '',
    phone: data.phone || '',
    email: data.email || '',
    address: data.address || '',
    city: data.city || '',
    postalCode: data.postalCode || '',
    country: data.country || 'España',
  });

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

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Users 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 Cliente
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          Datos de contacto y ubicación
        </p>
      </div>

      <div className="space-y-4">
        {/* Basic Info */}
        <div>
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
            <Building className="w-4 h-4" />
            Información Básica
          </h4>

          <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 Cliente / Empresa *
              </label>
              <input
                type="text"
                value={customerData.name}
                onChange={(e) => setCustomerData({ ...customerData, name: e.target.value })}
                placeholder="Ej: Restaurante El Molino"
                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">
                Tipo de Cliente *
              </label>
              <select
                value={customerData.customerType}
                onChange={(e) => setCustomerData({ ...customerData, customerType: 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="retail">Minorista</option>
                <option value="wholesale">Mayorista</option>
                <option value="event">Eventos</option>
                <option value="restaurant">Restaurante / Café</option>
                <option value="hotel">Hotel</option>
                <option value="other">Otro</option>
              </select>
            </div>

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

        {/* Contact Info */}
        <div>
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
            <Phone className="w-4 h-4" />
            Datos de Contacto
          </h4>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <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={customerData.phone}
                onChange={(e) => setCustomerData({ ...customerData, 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>
              <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={customerData.email}
                onChange={(e) => setCustomerData({ ...customerData, email: e.target.value })}
                placeholder="contacto@empresa.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>
        </div>

        {/* Address */}
        <div>
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
            <MapPin className="w-4 h-4" />
            Dirección
          </h4>

          <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">
                Dirección Completa
              </label>
              <textarea
                value={customerData.address}
                onChange={(e) => setCustomerData({ ...customerData, address: e.target.value })}
                placeholder="Calle, número, piso, etc..."
                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">
                Ciudad
              </label>
              <input
                type="text"
                value={customerData.city}
                onChange={(e) => setCustomerData({ ...customerData, city: e.target.value })}
                placeholder="Ciudad"
                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">
                Código Postal
              </label>
              <input
                type="text"
                value={customerData.postalCode}
                onChange={(e) => setCustomerData({ ...customerData, postalCode: e.target.value })}
                placeholder="28001"
                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>

      {/* Continue Button */}
      <div className="flex justify-end pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={handleContinue}
          disabled={!customerData.name || !customerData.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: Preferences & Terms
const PreferencesTermsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
  const [preferences, setPreferences] = useState({
    paymentTerms: data.paymentTerms || 'immediate',
    customPaymentDays: data.customPaymentDays || '',
    preferredDeliveryDays: data.preferredDeliveryDays || [],
    preferredDeliveryTime: data.preferredDeliveryTime || '',
    discountPercentage: data.discountPercentage || '',
    dietaryRestrictions: data.dietaryRestrictions || '',
    allergens: data.allergens || [],
    notes: data.notes || '',
  });

  const weekDays = [
    { id: 'monday', label: 'Lunes' },
    { id: 'tuesday', label: 'Martes' },
    { id: 'wednesday', label: 'Miércoles' },
    { id: 'thursday', label: 'Jueves' },
    { id: 'friday', label: 'Viernes' },
    { id: 'saturday', label: 'Sábado' },
    { id: 'sunday', label: 'Domingo' },
  ];

  const allergensList = [
    'Gluten',
    'Lácteos',
    'Huevos',
    'Frutos secos',
    'Soja',
    'Sésamo',
  ];

  const toggleDeliveryDay = (day: string) => {
    const days = preferences.preferredDeliveryDays as string[];
    if (days.includes(day)) {
      setPreferences({
        ...preferences,
        preferredDeliveryDays: days.filter((d) => d !== day),
      });
    } else {
      setPreferences({
        ...preferences,
        preferredDeliveryDays: [...days, day],
      });
    }
  };

  const toggleAllergen = (allergen: string) => {
    const allergens = preferences.allergens as string[];
    if (allergens.includes(allergen)) {
      setPreferences({
        ...preferences,
        allergens: allergens.filter((a) => a !== allergen),
      });
    } else {
      setPreferences({
        ...preferences,
        allergens: [...allergens, allergen],
      });
    }
  };

  const handleConfirm = () => {
    onDataChange({ ...data, ...preferences });
    // Here you would typically make an API call to save the customer
    console.log('Saving customer:', { ...data, ...preferences });
    onComplete();
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <CreditCard 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">
          Preferencias y Condiciones
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          Configura términos comerciales y preferencias
        </p>
      </div>

      <div className="space-y-4">
        {/* Payment Terms */}
        <div>
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
            <CreditCard className="w-4 h-4" />
            Términos de Pago
          </h4>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Condiciones de Pago
              </label>
              <select
                value={preferences.paymentTerms}
                onChange={(e) => setPreferences({ ...preferences, 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>
                <option value="custom">Personalizado</option>
              </select>
            </div>

            {preferences.paymentTerms === 'custom' && (
              <div>
                <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                  Días de Crédito
                </label>
                <input
                  type="number"
                  value={preferences.customPaymentDays}
                  onChange={(e) =>
                    setPreferences({ ...preferences, customPaymentDays: e.target.value })
                  }
                  placeholder="45"
                  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)]"
                  min="1"
                />
              </div>
            )}

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Descuento (%)
              </label>
              <input
                type="number"
                value={preferences.discountPercentage}
                onChange={(e) =>
                  setPreferences({ ...preferences, discountPercentage: e.target.value })
                }
                placeholder="10"
                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)]"
                min="0"
                max="100"
                step="0.1"
              />
              <p className="text-xs text-[var(--text-tertiary)] mt-1">
                Para clientes mayoristas
              </p>
            </div>
          </div>
        </div>

        {/* Delivery Preferences */}
        <div>
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
            <Calendar className="w-4 h-4" />
            Preferencias de Entrega
          </h4>

          <div className="space-y-3">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Días Preferidos de Entrega
              </label>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                {weekDays.map((day) => (
                  <button
                    key={day.id}
                    onClick={() => toggleDeliveryDay(day.id)}
                    className={`px-3 py-2 text-sm rounded-lg border-2 transition-all ${
                      (preferences.preferredDeliveryDays as string[]).includes(day.id)
                        ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/10 text-[var(--color-primary)] font-semibold'
                        : 'border-[var(--border-secondary)] text-[var(--text-secondary)]'
                    }`}
                  >
                    {day.label}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Hora Preferida
              </label>
              <input
                type="time"
                value={preferences.preferredDeliveryTime}
                onChange={(e) =>
                  setPreferences({ ...preferences, preferredDeliveryTime: e.target.value })
                }
                className="w-full md:w-48 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>

        {/* Dietary Restrictions & Allergens */}
        <div>
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
            <AlertTriangle className="w-4 h-4" />
            Restricciones y Alergias
          </h4>

          <div className="space-y-3">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Alergias Conocidas
              </label>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                {allergensList.map((allergen) => (
                  <button
                    key={allergen}
                    onClick={() => toggleAllergen(allergen)}
                    className={`px-3 py-2 text-sm rounded-lg border-2 transition-all ${
                      (preferences.allergens as string[]).includes(allergen)
                        ? 'border-red-500 bg-red-50 text-red-700 font-semibold'
                        : 'border-[var(--border-secondary)] text-[var(--text-secondary)]'
                    }`}
                  >
                    {allergen}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Otras Restricciones Dietéticas
              </label>
              <textarea
                value={preferences.dietaryRestrictions}
                onChange={(e) =>
                  setPreferences({ ...preferences, dietaryRestrictions: e.target.value })
                }
                placeholder="Ej: Vegano, sin azúcar, kosher, halal..."
                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>

        {/* Notes */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            Notas Adicionales
          </label>
          <textarea
            value={preferences.notes}
            onChange={(e) => setPreferences({ ...preferences, notes: e.target.value })}
            placeholder="Información adicional sobre el cliente, preferencias especiales, historial..."
            rows={3}
            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>

        {/* Summary */}
        <div className="p-4 bg-[var(--bg-secondary)]/50 rounded-lg border border-[var(--border-secondary)]">
          <h4 className="font-semibold text-[var(--text-primary)] mb-3">Resumen del Cliente</h4>
          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-[var(--text-secondary)]">Nombre:</span>
              <span className="font-medium">{data.name}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-[var(--text-secondary)]">Tipo:</span>
              <span className="font-medium capitalize">{data.customerType}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-[var(--text-secondary)]">Teléfono:</span>
              <span className="font-medium">{data.phone}</span>
            </div>
            {data.email && (
              <div className="flex justify-between">
                <span className="text-[var(--text-secondary)]">Email:</span>
                <span className="font-medium">{data.email}</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Confirm Button */}
      <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 Cliente
        </button>
      </div>
    </div>
  );
};

export const CustomerWizardSteps = (
  data: Record<string, any>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => [
  {
    id: 'customer-details',
    title: 'Detalles del Cliente',
    description: 'Información de contacto',
    component: (props) => <CustomerDetailsStep {...props} data={data} onDataChange={setData} />,
  },
  {
    id: 'customer-preferences',
    title: 'Preferencias y Términos',
    description: 'Condiciones comerciales',
    component: (props) => <PreferencesTermsStep {...props} data={data} onDataChange={setData} />,
    isOptional: true,
  },
];
