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';

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

const SupplierDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
  const { currentTenant } = useTenant();
  const [supplierData, setSupplierData] = useState({
    // Required fields
    name: data.name || '',
    supplierType: data.supplierType || 'ingredients',
    status: data.status || 'pending_approval',
    paymentTerms: data.paymentTerms || 'net_30',
    currency: data.currency || 'EUR',
    standardLeadTime: data.standardLeadTime || 3,

    // Basic optional fields
    contactPerson: data.contactPerson || '',
    email: data.email || '',
    phone: data.phone || '',

    // Advanced optional fields
    supplierCode: data.supplierCode || '',
    taxId: data.taxId || '',
    registrationNumber: data.registrationNumber || '',
    mobile: data.mobile || '',
    website: data.website || '',
    addressLine1: data.addressLine1 || '',
    addressLine2: data.addressLine2 || '',
    city: data.city || '',
    stateProvince: data.stateProvince || '',
    postalCode: data.postalCode || '',
    country: data.country || '',
    creditLimit: data.creditLimit || '',
    minimumOrderAmount: data.minimumOrderAmount || '',
    deliveryArea: data.deliveryArea || '',
    isPreferredSupplier: data.isPreferredSupplier || false,
    autoApproveEnabled: data.autoApproveEnabled || false,
    notes: data.notes || '',
    certifications: data.certifications || '',
    specializations: data.specializations || '',
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  useEffect(() => {
    onDataChange({ ...data, ...supplierData });
  }, [supplierData]);

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

    setLoading(true);
    setError(null);

    try {
      const payload = {
        name: supplierData.name,
        supplier_type: supplierData.supplierType,
        status: supplierData.status,
        payment_terms: supplierData.paymentTerms,
        currency: supplierData.currency,
        standard_lead_time: supplierData.standardLeadTime,
        supplier_code: supplierData.supplierCode || undefined,
        tax_id: supplierData.taxId || undefined,
        registration_number: supplierData.registrationNumber || undefined,
        contact_person: supplierData.contactPerson || undefined,
        email: supplierData.email || undefined,
        phone: supplierData.phone || undefined,
        mobile: supplierData.mobile || undefined,
        website: supplierData.website || undefined,
        address_line1: supplierData.addressLine1 || undefined,
        address_line2: supplierData.addressLine2 || undefined,
        city: supplierData.city || undefined,
        state_province: supplierData.stateProvince || undefined,
        postal_code: supplierData.postalCode || undefined,
        country: supplierData.country || undefined,
        credit_limit: supplierData.creditLimit ? parseFloat(supplierData.creditLimit) : undefined,
        minimum_order_amount: supplierData.minimumOrderAmount ? parseFloat(supplierData.minimumOrderAmount) : undefined,
        delivery_area: supplierData.deliveryArea || undefined,
        is_preferred_supplier: supplierData.isPreferredSupplier,
        auto_approve_enabled: supplierData.autoApproveEnabled,
        notes: supplierData.notes || undefined,
        certifications: supplierData.certifications ? JSON.parse(`{"items": ${JSON.stringify(supplierData.certifications.split(',').map(c => c.trim()))}}`) : undefined,
        specializations: supplierData.specializations ? JSON.parse(`{"items": ${JSON.stringify(supplierData.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');
      onComplete();
    } 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={supplierData.name}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.supplierType}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.status}
              onChange={(e) => setSupplierData({ ...supplierData, 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={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)] 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={supplierData.currency}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.standardLeadTime}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.contactPerson}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.email}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.phone}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.supplierCode}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.mobile}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.taxId}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.registrationNumber}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.website}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.addressLine1}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.addressLine2}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.city}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.stateProvince}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.postalCode}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.country}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.creditLimit}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.minimumOrderAmount}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.deliveryArea}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.isPreferredSupplier}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.autoApproveEnabled}
                onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.certifications}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.specializations}
              onChange={(e) => setSupplierData({ ...supplierData, 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={supplierData.notes}
              onChange={(e) => setSupplierData({ ...supplierData, 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 className="flex justify-center pt-4 border-t border-[var(--border-primary)]">
        <button
          type="button"
          onClick={handleCreateSupplier}
          disabled={loading}
          className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold inline-flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? (
            <>
              <Loader2 className="w-5 h-5 animate-spin" />
              Creating supplier...
            </>
          ) : (
            <>
              <CheckCircle2 className="w-5 h-5" />
              Create Supplier
            </>
          )}
        </button>
      </div>
    </div>
  );
};

export const SupplierWizardSteps = (
  data: Record<string, any>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => [
  {
    id: 'supplier-details',
    title: 'Supplier Details',
    description: 'Essential supplier information',
    component: (props) => <SupplierDetailsStep {...props} data={data} onDataChange={setData} />,
    validate: () => {
      return !!(
        data.name &&
        data.supplierType &&
        data.status &&
        data.paymentTerms &&
        data.currency &&
        data.standardLeadTime >= 0
      );
    },
  },
];
