import React, { useState, useEffect } from 'react';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { Building2, CheckCircle2, Loader2 } from 'lucide-react';
import { useTenant } from '../../../../stores/tenant.store';
import { suppliersService } from '../../../../api/services/suppliers';
import { showToast } from '../../../../utils/toast';
import { AdvancedOptionsSection } from '../../../ui/AdvancedOptionsSection';
import Tooltip from '../../../ui/Tooltip/Tooltip';

const SupplierDetailsStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange, onComplete }) => {
  // New architecture: access data from dataRef.current
  const data = dataRef?.current || {};
  const { currentTenant } = useTenant();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleFieldChange = (field: string, value: any) => {
    onDataChange?.({ ...data, [field]: value });
  };

  useEffect(() => {
    if (!data.supplierCode && data.name) {
      const code = `SUP-${data.name.substring(0, 3).toUpperCase()}-${Date.now().toString().slice(-4)}`;
      onDataChange?.({ ...data, supplierCode: code });
    }
  }, [data.name]);

  const handleCreateSupplier = async () => {
    if (!currentTenant?.id) {
      setError('Could not obtain tenant information');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const payload = {
        name: data.name,
        supplier_type: data.supplierType,
        status: data.status,
        payment_terms: data.paymentTerms,
        currency: data.currency,
        standard_lead_time: data.standardLeadTime,
        supplier_code: data.supplierCode || undefined,
        tax_id: data.taxId || undefined,
        registration_number: data.registrationNumber || undefined,
        contact_person: data.contactPerson || undefined,
        email: data.email || undefined,
        phone: data.phone || undefined,
        mobile: data.mobile || undefined,
        website: data.website || undefined,
        address_line1: data.addressLine1 || undefined,
        address_line2: data.addressLine2 || undefined,
        city: data.city || undefined,
        state_province: data.stateProvince || undefined,
        postal_code: data.postalCode || undefined,
        country: data.country || undefined,
        credit_limit: data.creditLimit ? parseFloat(data.creditLimit) : undefined,
        minimum_order_amount: data.minimumOrderAmount ? parseFloat(data.minimumOrderAmount) : undefined,
        delivery_area: data.deliveryArea || undefined,
        is_preferred_supplier: data.isPreferredSupplier,
        auto_approve_enabled: data.autoApproveEnabled,
        notes: data.notes || undefined,
        certifications: data.certifications ? JSON.parse(`{"items": ${JSON.stringify(data.certifications.split(',').map(c => c.trim()))}}`) : undefined,
        specializations: data.specializations ? JSON.parse(`{"items": ${JSON.stringify(data.specializations.split(',').map(s => s.trim()))}}`) : undefined,
        created_by: currentTenant.id,
        updated_by: currentTenant.id,
      };

      await suppliersService.createSupplier(currentTenant.id, payload);
      showToast.success('Supplier created successfully');
      // Let the wizard handle completion via the Next/Complete button
    } catch (err: any) {
      console.error('Error creating supplier:', err);
      const errorMessage = err.response?.data?.detail || 'Error creating supplier';
      setError(errorMessage);
      showToast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  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">Supplier Details</h3>
        <p className="text-sm text-[var(--text-secondary)]">Essential supplier information</p>
      </div>

      {error && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
          {error}
        </div>
      )}

      {/* Required Fields */}
      <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">
              Supplier Name *
            </label>
            <input
              type="text"
              value={data.name}
              onChange={(e) => handleFieldChange('name', e.target.value)}
              placeholder="e.g., Premium Flour Suppliers Ltd."
              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 inline-flex items-center gap-2">
              Supplier Type *
              <Tooltip content="Category of products/services this supplier provides">
                <span />
              </Tooltip>
            </label>
            <select
              value={data.supplierType}
              onChange={(e) => handleFieldChange('supplierType', 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="ingredients">Ingredients</option>
              <option value="packaging">Packaging</option>
              <option value="equipment">Equipment</option>
              <option value="services">Services</option>
              <option value="utilities">Utilities</option>
              <option value="multi">Multi</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Status *
            </label>
            <select
              value={data.status}
              onChange={(e) => handleFieldChange('status', 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="active">Active</option>
              <option value="inactive">Inactive</option>
              <option value="pending_approval">Pending Approval</option>
              <option value="suspended">Suspended</option>
              <option value="blacklisted">Blacklisted</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Payment Terms *
            </label>
            <select
              value={data.paymentTerms}
              onChange={(e) => handleFieldChange('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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            >
              <option value="cod">COD (Cash on Delivery)</option>
              <option value="net_15">Net 15</option>
              <option value="net_30">Net 30</option>
              <option value="net_45">Net 45</option>
              <option value="net_60">Net 60</option>
              <option value="prepaid">Prepaid</option>
              <option value="credit_terms">Credit Terms</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Currency *
            </label>
            <input
              type="text"
              value={data.currency}
              onChange={(e) => handleFieldChange('currency', e.target.value)}
              placeholder="EUR"
              maxLength={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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
              Standard Lead Time (days) *
              <Tooltip content="Typical delivery time from order to delivery">
                <span />
              </Tooltip>
            </label>
            <input
              type="number"
              value={data.standardLeadTime}
              onChange={(e) => handleFieldChange('standardLeadTime', parseInt(e.target.value) || 0)}
              placeholder="3"
              min="0"
              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>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Contact Person
            </label>
            <input
              type="text"
              value={data.contactPerson}
              onChange={(e) => handleFieldChange('contactPerson', e.target.value)}
              placeholder="John Doe"
              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">
              Email
            </label>
            <input
              type="email"
              value={data.email}
              onChange={(e) => handleFieldChange('email', e.target.value)}
              placeholder="contact@supplier.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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Phone
            </label>
            <input
              type="tel"
              value={data.phone}
              onChange={(e) => handleFieldChange('phone', e.target.value)}
              placeholder="+1 234 567 8900"
              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>
      </div>

      {/* Advanced Options */}
      <AdvancedOptionsSection
        title="Advanced Options"
        description="Additional supplier information and business details"
      >
        <div className="space-y-4">
          <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">
                Supplier Code
              </label>
              <input
                type="text"
                value={data.supplierCode}
                onChange={(e) => handleFieldChange('supplierCode', e.target.value)}
                placeholder="SUP-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">
                Mobile
              </label>
              <input
                type="tel"
                value={data.mobile}
                onChange={(e) => handleFieldChange('mobile', e.target.value)}
                placeholder="+1 234 567 8900"
                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">
                Tax ID
              </label>
              <input
                type="text"
                value={data.taxId}
                onChange={(e) => handleFieldChange('taxId', e.target.value)}
                placeholder="VAT/Tax ID"
                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">
                Registration Number
              </label>
              <input
                type="text"
                value={data.registrationNumber}
                onChange={(e) => handleFieldChange('registrationNumber', e.target.value)}
                placeholder="Business registration number"
                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 className="md:col-span-2">
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Website
              </label>
              <input
                type="url"
                value={data.website}
                onChange={(e) => handleFieldChange('website', e.target.value)}
                placeholder="https://www.supplier.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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
              />
            </div>

            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Address Line 1
              </label>
              <input
                type="text"
                value={data.addressLine1}
                onChange={(e) => handleFieldChange('addressLine1', e.target.value)}
                placeholder="Street address"
                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 className="md:col-span-2">
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Address Line 2
              </label>
              <input
                type="text"
                value={data.addressLine2}
                onChange={(e) => handleFieldChange('addressLine2', e.target.value)}
                placeholder="Suite, building, etc."
                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">
                City
              </label>
              <input
                type="text"
                value={data.city}
                onChange={(e) => handleFieldChange('city', e.target.value)}
                placeholder="City"
                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">
                State/Province
              </label>
              <input
                type="text"
                value={data.stateProvince}
                onChange={(e) => handleFieldChange('stateProvince', e.target.value)}
                placeholder="State"
                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">
                Postal Code
              </label>
              <input
                type="text"
                value={data.postalCode}
                onChange={(e) => handleFieldChange('postalCode', e.target.value)}
                placeholder="12345"
                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">
                Country
              </label>
              <input
                type="text"
                value={data.country}
                onChange={(e) => handleFieldChange('country', e.target.value)}
                placeholder="Country"
                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">
                Credit Limit
              </label>
              <input
                type="number"
                value={data.creditLimit}
                onChange={(e) => handleFieldChange('creditLimit', e.target.value)}
                placeholder="10000.00"
                min="0"
                step="0.01"
                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">
                Minimum Order Amount
              </label>
              <input
                type="number"
                value={data.minimumOrderAmount}
                onChange={(e) => handleFieldChange('minimumOrderAmount', e.target.value)}
                placeholder="100.00"
                min="0"
                step="0.01"
                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 className="md:col-span-2">
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Delivery Area
              </label>
              <input
                type="text"
                value={data.deliveryArea}
                onChange={(e) => handleFieldChange('deliveryArea', e.target.value)}
                placeholder="e.g., New York Metro Area"
                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>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="isPreferredSupplier"
                checked={data.isPreferredSupplier}
                onChange={(e) => handleFieldChange('isPreferredSupplier', e.target.checked)}
                className="w-4 h-4 text-[var(--color-primary)] border-[var(--border-secondary)] rounded focus:ring-2 focus:ring-[var(--color-primary)]"
              />
              <label htmlFor="isPreferredSupplier" className="text-sm font-medium text-[var(--text-secondary)]">
                Preferred Supplier
              </label>
            </div>

            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="autoApproveEnabled"
                checked={data.autoApproveEnabled}
                onChange={(e) => handleFieldChange('autoApproveEnabled', e.target.checked)}
                className="w-4 h-4 text-[var(--color-primary)] border-[var(--border-secondary)] rounded focus:ring-2 focus:ring-[var(--color-primary)]"
              />
              <label htmlFor="autoApproveEnabled" className="text-sm font-medium text-[var(--text-secondary)]">
                Auto-approve Orders
              </label>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Certifications
            </label>
            <input
              type="text"
              value={data.certifications}
              onChange={(e) => handleFieldChange('certifications', e.target.value)}
              placeholder="e.g., ISO 9001, HACCP, Organic (comma-separated)"
              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">
              Specializations
            </label>
            <input
              type="text"
              value={data.specializations}
              onChange={(e) => handleFieldChange('specializations', e.target.value)}
              placeholder="e.g., Organic flours, Gluten-free products (comma-separated)"
              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">
              Notes
            </label>
            <textarea
              value={data.notes}
              onChange={(e) => handleFieldChange('notes', e.target.value)}
              placeholder="Additional notes about this supplier..."
              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)]"
              rows={3}
            />
          </div>
        </div>
      </AdvancedOptionsSection>

    </div>
  );
};

export const SupplierWizardSteps = (
  dataRef: React.MutableRefObject<Record<string, any>>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => {
  // New architecture: return direct component reference instead of arrow function
  // dataRef and onDataChange are now passed through WizardModal props
  return [
    {
      id: 'supplier-details',
      title: 'Supplier Details',
      description: 'Essential supplier information',
      component: SupplierDetailsStep,
    },
  ];
};
