import React, { useState, useEffect } from 'react';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { Users, CheckCircle2, Loader2 } from 'lucide-react';
import { useTenant } from '../../../../stores/tenant.store';
import OrdersService from '../../../../api/services/orders';
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 CustomerDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
  const { currentTenant } = useTenant();
  const [customerData, setCustomerData] = useState({
    // Required fields
    name: data.name || '',
    customerCode: data.customerCode || '',
    customerType: data.customerType || 'individual',
    country: data.country || 'US',

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

    // Advanced optional fields
    addressLine1: data.addressLine1 || '',
    addressLine2: data.addressLine2 || '',
    city: data.city || '',
    state: data.state || '',
    postalCode: data.postalCode || '',
    taxId: data.taxId || '',
    businessLicense: data.businessLicense || '',
    paymentTerms: data.paymentTerms || 'immediate',
    creditLimit: data.creditLimit || '',
    discountPercentage: data.discountPercentage || 0,
    customerSegment: data.customerSegment || 'regular',
    priorityLevel: data.priorityLevel || 'normal',
    preferredDeliveryMethod: data.preferredDeliveryMethod || 'delivery',
    specialInstructions: data.specialInstructions || '',
  });

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

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

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

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

    setLoading(true);
    setError(null);

    try {
      const payload = {
        name: customerData.name,
        customer_code: customerData.customerCode,
        customer_type: customerData.customerType,
        country: customerData.country,
        business_name: customerData.businessName || undefined,
        email: customerData.email || undefined,
        phone: customerData.phone || undefined,
        address_line1: customerData.addressLine1 || undefined,
        address_line2: customerData.addressLine2 || undefined,
        city: customerData.city || undefined,
        state: customerData.state || undefined,
        postal_code: customerData.postalCode || undefined,
        tax_id: customerData.taxId || undefined,
        business_license: customerData.businessLicense || undefined,
        payment_terms: customerData.paymentTerms,
        credit_limit: customerData.creditLimit ? parseFloat(customerData.creditLimit) : undefined,
        discount_percentage: customerData.discountPercentage,
        customer_segment: customerData.customerSegment,
        priority_level: customerData.priorityLevel,
        preferred_delivery_method: customerData.preferredDeliveryMethod,
        special_instructions: customerData.specialInstructions || undefined,
        is_active: true,
      };

      await OrdersService.createCustomer(currentTenant.id, payload);
      showToast.success('Customer created successfully');
      onComplete();
    } catch (err: any) {
      console.error('Error creating customer:', err);
      const errorMessage = err.response?.data?.detail || 'Error creating customer';
      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)]">
        <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">Customer Details</h3>
        <p className="text-sm text-[var(--text-secondary)]">Essential customer 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>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Customer Name *
            </label>
            <input
              type="text"
              value={customerData.name}
              onChange={(e) => setCustomerData({ ...customerData, name: e.target.value })}
              placeholder="e.g., Restaurant 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)] 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">
              Customer Code *
              <Tooltip content="Unique identifier for this customer. Auto-generated but editable.">
                <span />
              </Tooltip>
            </label>
            <input
              type="text"
              value={customerData.customerCode}
              onChange={(e) => setCustomerData({ ...customerData, customerCode: e.target.value })}
              placeholder="CUST-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>

        <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">
              Customer Type *
            </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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            >
              <option value="individual">Individual</option>
              <option value="business">Business</option>
              <option value="central_bakery">Central Bakery</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Country *
            </label>
            <input
              type="text"
              value={customerData.country}
              onChange={(e) => setCustomerData({ ...customerData, country: e.target.value })}
              placeholder="US"
              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>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            Business Name
          </label>
          <input
            type="text"
            value={customerData.businessName}
            onChange={(e) => setCustomerData({ ...customerData, businessName: e.target.value })}
            placeholder="Legal business name"
            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="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Email
            </label>
            <input
              type="email"
              value={customerData.email}
              onChange={(e) => setCustomerData({ ...customerData, email: e.target.value })}
              placeholder="contact@company.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={customerData.phone}
              onChange={(e) => setCustomerData({ ...customerData, 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 customer information and business terms"
      >
        <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">
                Address Line 1
              </label>
              <input
                type="text"
                value={customerData.addressLine1}
                onChange={(e) => setCustomerData({ ...customerData, 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={customerData.addressLine2}
                onChange={(e) => setCustomerData({ ...customerData, addressLine2: e.target.value })}
                placeholder="Apartment, suite, 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={customerData.city}
                onChange={(e) => setCustomerData({ ...customerData, 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={customerData.state}
                onChange={(e) => setCustomerData({ ...customerData, state: 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={customerData.postalCode}
                onChange={(e) => setCustomerData({ ...customerData, 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">
                Tax ID
              </label>
              <input
                type="text"
                value={customerData.taxId}
                onChange={(e) => setCustomerData({ ...customerData, taxId: e.target.value })}
                placeholder="Tax identification 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>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Business License
              </label>
              <input
                type="text"
                value={customerData.businessLicense}
                onChange={(e) => setCustomerData({ ...customerData, businessLicense: e.target.value })}
                placeholder="Business license 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>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Payment Terms
              </label>
              <select
                value={customerData.paymentTerms}
                onChange={(e) => setCustomerData({ ...customerData, 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="immediate">Immediate</option>
                <option value="net_30">Net 30</option>
                <option value="net_60">Net 60</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Credit Limit
              </label>
              <input
                type="number"
                value={customerData.creditLimit}
                onChange={(e) => setCustomerData({ ...customerData, creditLimit: e.target.value })}
                placeholder="5000.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">
                Discount Percentage
              </label>
              <input
                type="number"
                value={customerData.discountPercentage}
                onChange={(e) => setCustomerData({ ...customerData, discountPercentage: parseFloat(e.target.value) || 0 })}
                placeholder="10"
                min="0"
                max="100"
                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">
                Customer Segment
              </label>
              <select
                value={customerData.customerSegment}
                onChange={(e) => setCustomerData({ ...customerData, customerSegment: 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="vip">VIP</option>
                <option value="regular">Regular</option>
                <option value="wholesale">Wholesale</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Priority Level
              </label>
              <select
                value={customerData.priorityLevel}
                onChange={(e) => setCustomerData({ ...customerData, priorityLevel: 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="high">High</option>
                <option value="normal">Normal</option>
                <option value="low">Low</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                Preferred Delivery Method
              </label>
              <select
                value={customerData.preferredDeliveryMethod}
                onChange={(e) => setCustomerData({ ...customerData, preferredDeliveryMethod: 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="delivery">Delivery</option>
                <option value="pickup">Pickup</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Special Instructions
            </label>
            <textarea
              value={customerData.specialInstructions}
              onChange={(e) => setCustomerData({ ...customerData, specialInstructions: e.target.value })}
              placeholder="Any special notes or instructions for this customer..."
              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={handleCreateCustomer}
          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 customer...
            </>
          ) : (
            <>
              <CheckCircle2 className="w-5 h-5" />
              Create Customer
            </>
          )}
        </button>
      </div>
    </div>
  );
};

export const CustomerWizardSteps = (
  data: Record<string, any>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => [
  {
    id: 'customer-details',
    title: 'Customer Details',
    description: 'Contact and business information',
    component: (props) => <CustomerDetailsStep {...props} data={data} onDataChange={setData} />,
    validate: () => {
      return !!(data.name && data.customerCode && data.customerType && data.country);
    },
  },
];
