import React, { useState } from 'react';
import { Users } from 'lucide-react';
import { WizardModal, WizardStep } from '../../../ui/WizardModal/WizardModal';
import { SupplierBasicStep } from './SupplierBasicStep';
import { SupplierDeliveryStep } from './SupplierDeliveryStep';
import { SupplierReviewStep } from './SupplierReviewStep';
import type { SupplierCreate, SupplierType, SupplierStatus, PaymentTerms } from '../../../../api/types/suppliers';

interface SupplierWizardModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreateSupplier: (supplierData: SupplierCreate) => Promise<void>;
}

export const SupplierWizardModal: React.FC<SupplierWizardModalProps> = ({
  isOpen,
  onClose,
  onCreateSupplier
}) => {
  // Supplier state
  const [supplierData, setSupplierData] = useState<Partial<SupplierCreate>>({
    status: 'pending_approval' as SupplierStatus,
    payment_terms: 'net_30' as PaymentTerms,
    quality_rating: 0,
    delivery_rating: 0,
    pricing_rating: 0,
    overall_rating: 0
  });

  const handleUpdate = (data: Partial<SupplierCreate>) => {
    setSupplierData(data);
  };

  const handleComplete = async () => {
    try {
      // Generate supplier code if not provided
      const supplierCode = supplierData.supplier_code ||
        (supplierData.name?.substring(0, 3).toUpperCase() || 'SUP') +
        String(Date.now()).slice(-3);

      // Build final supplier data
      const finalSupplierData: SupplierCreate = {
        name: supplierData.name!,
        supplier_code: supplierCode,
        tax_id: supplierData.tax_id || null,
        registration_number: supplierData.registration_number || null,
        supplier_type: supplierData.supplier_type!,
        status: supplierData.status || ('pending_approval' as SupplierStatus),
        contact_person: supplierData.contact_person || null,
        email: supplierData.email || null,
        phone: supplierData.phone || null,
        website: supplierData.website || null,
        address_street: supplierData.address_street || null,
        address_city: supplierData.address_city || null,
        address_state: supplierData.address_state || null,
        address_postal_code: supplierData.address_postal_code || null,
        address_country: supplierData.address_country || null,
        payment_terms: supplierData.payment_terms!,
        credit_limit: supplierData.credit_limit || null,
        currency: supplierData.currency || 'EUR',
        tax_rate: supplierData.tax_rate || null,
        lead_time_days: supplierData.lead_time_days || null,
        minimum_order_value: supplierData.minimum_order_value || null,
        delivery_schedule: supplierData.delivery_schedule || null,
        preferred_delivery_method: supplierData.preferred_delivery_method || null,
        bank_account: supplierData.bank_account || null,
        bank_name: supplierData.bank_name || null,
        swift_code: supplierData.swift_code || null,
        certifications: supplierData.certifications || null,
        quality_rating: supplierData.quality_rating || 0,
        delivery_rating: supplierData.delivery_rating || 0,
        pricing_rating: supplierData.pricing_rating || 0,
        overall_rating: supplierData.overall_rating || 0,
        sustainability_practices: supplierData.sustainability_practices || null,
        insurance_info: supplierData.insurance_info || null,
        notes: supplierData.notes || null,
        business_hours: supplierData.business_hours || null,
        specializations: supplierData.specializations || null
      };

      await onCreateSupplier(finalSupplierData);

      // Reset state
      setSupplierData({
        status: 'pending_approval' as SupplierStatus,
        payment_terms: 'net_30' as PaymentTerms,
        quality_rating: 0,
        delivery_rating: 0,
        pricing_rating: 0,
        overall_rating: 0
      });
    } catch (error) {
      console.error('Error creating supplier:', error);
      throw error;
    }
  };

  // Define wizard steps
  const steps: WizardStep[] = [
    {
      id: 'basic',
      title: 'Información Básica',
      description: 'Datos esenciales del proveedor',
      component: (props) => (
        <SupplierBasicStep
          {...props}
          supplierData={supplierData}
          onUpdate={handleUpdate}
        />
      ),
      validate: () => {
        return !!(supplierData.name && supplierData.name.trim().length >= 1 && supplierData.supplier_type);
      }
    },
    {
      id: 'delivery',
      title: 'Entrega y Términos',
      description: 'Términos de pago y entrega',
      component: (props) => (
        <SupplierDeliveryStep
          {...props}
          supplierData={supplierData}
          onUpdate={handleUpdate}
        />
      ),
      validate: () => {
        return !!supplierData.payment_terms;
      }
    },
    {
      id: 'review',
      title: 'Revisión',
      description: 'Detalles adicionales y revisión',
      component: (props) => (
        <SupplierReviewStep
          {...props}
          supplierData={supplierData}
          onUpdate={handleUpdate}
        />
      )
    }
  ];

  return (
    <WizardModal
      isOpen={isOpen}
      onClose={onClose}
      onComplete={handleComplete}
      title="Nuevo Proveedor"
      steps={steps}
      icon={<Users className="w-6 h-6" />}
      size="xl"
    />
  );
};
