import React, { useState, useEffect, useCallback, useRef } from 'react';
import { CheckCircle, User, Phone, MapPin, Loader2, Truck } from 'lucide-react';
import { Product, Order, SiteSettings } from '../types';
import { pushToDataLayer, gtmEvents } from '../utils/tagmeneger';
import { api } from '../lib/api';
import { getDisplayName } from '../lib/displayName';

// API Base URL
const API_BASE = '/api';

// Resolve current store slug from subdomain or localStorage
const getStoreSlug = (): string => {
  try {
    const parts = window.location.hostname.split('.');
    if (parts.length >= 2 && parts[0] !== 'www' && parts[0] !== 'localhost' && !/^\d+$/.test(parts[0])) return parts[0];
    return localStorage.getItem('preview_store_slug') || '';
  } catch { return ''; }
};

interface InlineOrderFormProps {
  product: Product;
  selectedSize: string;
  addOrder: (order: Order) => void;
  settings: SiteSettings;
}

const InlineOrderForm: React.FC<InlineOrderFormProps> = ({
  product,
  selectedSize,
  addOrder,
  settings
}) => {
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    address: ''
  });

  const defaultDeliveryZones = [
    { id: 'inside_ctg', name: 'inside Dhaka', charge: 70 },
    { id: 'outside_ctg', name: 'Outside Dhaka', charge: 130 }
  ];
  const deliveryZones = settings?.deliveryZones?.length ? settings.deliveryZones : defaultDeliveryZones;

  const [selectedZoneId, setSelectedZoneId] = useState(deliveryZones[0]?.id);
  const selectedZone = deliveryZones.find(z => z.id === selectedZoneId) || deliveryZones[0];

  const [isSubmitted, setIsSubmitted] = useState(false);
  const isSubmittedRef = useRef(false);
  const [isLoading, setIsLoading] = useState(false);
  const [hasInteracted, setHasInteracted] = useState(false);
  const [phoneError, setPhoneError] = useState('');
  const [stockChecking, setStockChecking] = useState(false);
  const [stockErrors, setStockErrors] = useState<string[]>([]);

  const sessionIdRef = useRef<string>(localStorage.getItem('shophyfast_checkout_session') || `SID-${Math.random().toString(36).substr(2, 9)}-${Date.now()}`);
  const orderIdRef = useRef<string>(`ORD-${Date.now()}`);
  const nameInputRef = useRef<HTMLInputElement>(null);
  const leadSaveTimeoutRef = useRef<NodeJS.Timeout>(undefined);

  // Check if selected size has free delivery
  const isFreeDeliveryEligible = useCallback((): boolean => {
    if (!product || !selectedSize) return false;

    if (product.priceConfigs && product.priceConfigs[selectedSize]) {
      return product.priceConfigs[selectedSize].freeDelivery === true;
    }

    const isKgSize = selectedSize.includes('কেজি') || selectedSize.includes('kg');
    return isKgSize && product.freeDeliveryEnabled === true;
  }, [product, selectedSize]);

  const currentPrice = product.priceMap?.[selectedSize] || product.price || 0;
  const freeDeliveryEligible = isFreeDeliveryEligible();
  const deliveryCharge = freeDeliveryEligible ? 0 : (selectedZone?.charge || 0);
  const total = currentPrice + deliveryCharge;

  // Phone number validation function
  const validatePhone = (phone: string): { isValid: boolean; cleanNumber: string; error: string } => {
    let numbers = phone.replace(/\D/g, '');

    if (numbers.startsWith('880')) {
      if (numbers.length >= 13) {
        numbers = numbers.substring(3);
        if (numbers.length === 10) {
          numbers = '0' + numbers;
        }
      }
      else if (numbers.length > 3) {
        numbers = numbers.substring(3);
      }
      else {
        numbers = '';
      }
    }

    if (numbers.length === 10 && !numbers.startsWith('01')) {
      numbers = '0' + numbers;
    }

    numbers = numbers.slice(0, 11);

    if (numbers.length === 0) {
      return { isValid: false, cleanNumber: '', error: '' };
    }

    if (numbers.length < 11) {
      return { isValid: false, cleanNumber: numbers, error: `${11 - numbers.length} digits remaining` };
    }

    if (!numbers.startsWith('01')) {
      return { isValid: false, cleanNumber: numbers, error: 'Must start with 01' };
    }

    const thirdDigit = numbers.charAt(2);
    if (!['3', '4', '5', '6', '7', '8', '9'].includes(thirdDigit)) {
      return { isValid: false, cleanNumber: numbers, error: 'Invalid mobile number' };
    }

    return { isValid: true, cleanNumber: numbers, error: '' };
  };

  // Handle phone change
  const handlePhoneChange = (value: string) => {
    const validation = validatePhone(value);
    setFormData(prev => ({ ...prev, phone: validation.cleanNumber }));
    setPhoneError(validation.error);
    setHasInteracted(true);
  };

  // Format phone for display
  const getFormattedPhone = () => {
    if (formData.phone.length === 11) {
      return formData.phone.replace(/(\d{4})(\d{3})(\d{4})/, '$1-$2-$3');
    }
    return formData.phone;
  };

  // Check stock before submitting order
  const checkStockBeforeOrder = async (): Promise<boolean> => {
    setStockChecking(true);
    setStockErrors([]);

    try {
      const errors: string[] = [];
      const stockCheck = await api.products.checkStock(product.id, 1, selectedSize);

      if (!stockCheck.success) {
        console.warn('Stock check API failed, proceeding with order');
      } else if (stockCheck.available === false) {
        const available = typeof stockCheck.stock === 'number' ? stockCheck.stock : 0;
        errors.push(`${getDisplayName(product.nameBangla, product.name)} এ স্টক নেই (${selectedSize}) — বর্তমান স্টক: ${available}`);
      }

      if (errors.length > 0) {
        setStockErrors(errors);
        return false;
      }

      return true;
    } catch (error) {
      console.error('Error checking stock:', error);
      return true;
    } finally {
      setStockChecking(false);
    }
  };

  // Save lead to PHP API
  const saveLeadToAPI = useCallback(async () => {
    const validation = validatePhone(formData.phone);
    if (!validation.isValid) return;

    try {
      const productContext = `${getDisplayName(product.nameBangla, product.name)} (${selectedSize})`;
      const locationText = selectedZone ? selectedZone.name : '';
      const fullAddress = formData.address
        ? `${formData.address} (${locationText})`
        : null;

      const payload = {
        phone: validation.cleanNumber,
        customer_name: formData.name || null,
        address: fullAddress,
        product_context: productContext,
        status: 'partial_entry',
        store_slug: getStoreSlug(),
      };

      const response = await fetch(`${API_BASE}/shop/leads`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Tenant-Slug': getStoreSlug() },
        body: JSON.stringify(payload)
      });

      if (!response.ok) throw new Error('Failed to save lead');
    } catch (err) {
      console.error('Lead save failed:', err);
    }
  }, [formData, product, selectedSize, selectedZone]);

  // Lead auto-save
  useEffect(() => {
    if (!hasInteracted) return;

    const validation = validatePhone(formData.phone);
    if (!validation.isValid) return;

    if (leadSaveTimeoutRef.current) {
      clearTimeout(leadSaveTimeoutRef.current);
    }

    leadSaveTimeoutRef.current = setTimeout(() => {
      if (!isSubmittedRef.current) {
        saveLeadToAPI();
      }
    }, 3000);

    return () => {
      if (leadSaveTimeoutRef.current) {
        clearTimeout(leadSaveTimeoutRef.current);
      }
    };
  }, [formData, hasInteracted, saveLeadToAPI]);

  // Lead save on exit
  useEffect(() => {
    const handleBeforeUnload = () => {
      const validation = validatePhone(formData.phone);
      if (validation.isValid && !isSubmittedRef.current) {
        saveLeadToAPI();
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      const validation = validatePhone(formData.phone);
      if (validation.isValid && !isSubmittedRef.current) {
        saveLeadToAPI();
      }
    };
  }, [formData, saveLeadToAPI]);

  useEffect(() => {
    if (!localStorage.getItem('shophyfast_checkout_session')) {
      localStorage.setItem('shophyfast_checkout_session', sessionIdRef.current);
    }
  }, []);

  // =====================================================
  // ✅ BEGIN_CHECKOUT EVENT - ফর্ম লোড হলে GTM-এ ইভেন্ট পাঠায়
  // =====================================================
  useEffect(() => {
    // Prepare checkout items for GTM
    const checkoutItems = [{
      item_id: product.id,
      item_name: product.name,
      item_name_bn: product.nameBangla || '',
      item_category: product.category || '',
      item_variant: selectedSize,
      price: currentPrice,
      quantity: 1,
    }];

    // Push begin_checkout event to GTM/GA4
    pushToDataLayer('begin_checkout', {
      event: 'begin_checkout',
      ecommerce: {
        currency: 'BDT',
        value: total,
        items: checkoutItems,
        checkout_step: 1,
        checkout_option: 'Cash on Delivery'
      }
    });

  }, [product.id, selectedSize, currentPrice, total]);

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setHasInteracted(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const validation = validatePhone(formData.phone);
    if (!validation.isValid) {
      alert('সঠিক ১১ সংখ্যার মোবাইল নম্বর দিন (যেমন: 017XXXXXXXX)');
      return;
    }

    setIsLoading(true);

    try {
      const stockAvailable = await checkStockBeforeOrder();
      if (!stockAvailable) {
        setIsLoading(false);
        return;
      }

      const items = [{
        productId: product.id,
        name: product.name,
        price: currentPrice,
        quantity: 1,
        size: selectedSize
      }];

      const locationText = selectedZone ? selectedZone.name : '';
      const fullAddress = `${formData.address} (${locationText})`;

      const orderPayload = {
        id: orderIdRef.current,
        session_id: sessionIdRef.current,
        customer_name: formData.name || 'Anonymous',
        phone: validation.cleanNumber,
        address: fullAddress,
        items: items,
        subtotal: currentPrice,
        delivery_charge: deliveryCharge,
        total: total,
        status: 'Confirmed Order',
        source: 'Landing Page Inline Form',
        confirmed_at: new Date().toISOString(),
        store_slug: getStoreSlug(),
      };

      const mappedItems = items.map(item => ({
        product_id: item.productId,
        name: item.name,
        qty: item.quantity,
        price: item.price
      }));

      const finalOrderPayload = {
        ...orderPayload,
        customer_phone: orderPayload.phone,
        customer_address: orderPayload.address,
        payment_method: 'cod',
        items: mappedItems,
      };

      const orderResponse = await fetch(`${API_BASE}/shop/checkout`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Tenant-Slug': getStoreSlug() },
        body: JSON.stringify(finalOrderPayload)
      });

      const orderData = await orderResponse.json();
      if (!orderData.success && !orderResponse.ok) {
        console.error('Validation errors:', orderData.errors);
        throw new Error(orderData.message || orderData.error || 'Order save failed');
      } else if (!orderData.success) {
        throw new Error(orderData.error || 'Order save failed');
      }

      try {
        await fetch(`${API_BASE}/shop/leads?phone=${validation.cleanNumber}`, { method: 'DELETE', headers: { 'X-Tenant-Slug': getStoreSlug() } });
      } catch (e) { }

      localStorage.removeItem('shophyfast_checkout_session');

      // ✅ Full purchase event — GA4 + Facebook Pixel
      gtmEvents.purchase({
        orderId: orderIdRef.current,
        items: [{ item_id: product.id, item_name: product.name, item_name_bn: product.nameBangla, item_category: product.category, item_variant: selectedSize, price: currentPrice, quantity: 1 }],
        subtotal: currentPrice,
        deliveryCharge,
        total,
        source: 'Landing Page Inline Form',
      });

      setIsSubmitted(true);
      isSubmittedRef.current = true;

      addOrder({
        id: orderIdRef.current,
        session_id: sessionIdRef.current,
        customerName: formData.name,
        phone: validation.cleanNumber,
        address: fullAddress,
        items,
        subtotal: currentPrice,
        deliveryCharge,
        total,
        status: 'Confirmed Order',
        source: 'Landing Page Inline Form',
        date: new Date().toISOString(),
        confirmed_at: new Date().toISOString()
      });

    } catch (err: any) {
      console.error('Order save error:', err);
      alert('অর্ডার সম্পন্ন করা সম্ভব হয়নি। আবার চেষ্টা করুন।');
    } finally {
      setIsLoading(false);
    }
  };

  if (isSubmitted) {
    return (
      <div className="bg-green-50 rounded-[40px] p-10 text-center border border-green-100 animate-scale-up">
        <div className="w-20 h-20 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-8 shadow-inner">
          <CheckCircle size={40} />
        </div>
        <h2 className="text-3xl font-black mb-4 font-bangla text-slate-900">অর্ডার সফল হয়েছে!</h2>
        <p className="text-slate-600 font-bangla text-lg">আমাদের প্রতিনিধি শীঘ্রই কল করে আপনার অর্ডারটি কনফার্ম করবেন।।</p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="space-y-6">
        <div>
          <label className="text-xs font-black text-slate-500 mb-2 block uppercase tracking-widest">আপনার নাম *</label>
          <div className="relative">
            <User className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400" size={20} />
            <input
              ref={nameInputRef}
              type="text"
              required
              autoComplete="name"
              className="w-full pl-14 pr-5 py-5 bg-white border-2 border-slate-100 focus:border-red-600 rounded-2xl font-bold transition-all text-slate-900 placeholder:text-slate-300 shadow-sm"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              placeholder="আপনার নাম লিখুন"
            />
          </div>
        </div>

        <div>
          <label className="text-xs font-black text-slate-500 mb-2 block uppercase tracking-widest">মোবাইল নম্বর *</label>
          <div className="relative">
            <Phone className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400" size={20} />
            <input
              type="tel"
              required
              autoComplete="tel"
              maxLength={14}
              className="w-full pl-14 pr-5 py-5 bg-white border-2 border-slate-100 focus:border-red-600 rounded-2xl font-bold transition-all text-slate-900 placeholder:text-slate-300 shadow-sm"
              value={formData.phone}
              onChange={(e) => handlePhoneChange(e.target.value)}
              placeholder="017XXXXXXXX"
            />
          </div>
          {formData.phone.length > 0 && (
            <div className="mt-1 px-1">
              {phoneError ? (
                <p className="text-[10px] text-red-500 font-bold">{phoneError}</p>
              ) : (
                formData.phone.length === 11 && (
                  <p className="text-[10px] text-green-500 font-bold">✅ {getFormattedPhone()}</p>
                )
              )}
            </div>
          )}
        </div>

        <div>
          <label className="text-xs font-black text-slate-500 mb-2 block uppercase tracking-widest">বিস্তারিত ঠিকানা *</label>
          <div className="relative">
            <MapPin className="absolute left-5 top-5 text-slate-400" size={20} />
            <textarea
              required
              autoComplete="street-address"
              className="w-full pl-14 pr-5 py-5 bg-white border-2 border-slate-100 focus:border-red-600 rounded-2xl font-bold transition-all text-slate-900 placeholder:text-slate-300 shadow-sm min-h-[120px]"
              value={formData.address}
              onChange={(e) => handleInputChange('address', e.target.value)}
              placeholder="বাসা নম্বর, রোড নম্বর, এলাকা..."
            />
          </div>
        </div>

        <div>
          <label className="text-xs font-black text-slate-500 mb-4 block uppercase tracking-widest text-center">📍 ডেলিভারি এরিয়া *</label>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {deliveryZones.map(zone => (
              <button
                key={zone.id}
                type="button"
                onClick={() => setSelectedZoneId(zone.id)}
                className={`p-3 rounded-xl border-2 font-bold transition-all text-center flex flex-col items-center justify-center gap-0.5 ${selectedZoneId === zone.id
                  ? 'bg-white border-red-600 text-slate-900 shadow-md shadow-red-600/5'
                  : 'bg-white border-slate-100 text-slate-400 hover:border-red-100'
                  }`}
              >
                <span className="font-bold text-sm">{zone.name}</span>
                <span className={`text-[10px] uppercase tracking-wider font-black ${selectedZoneId === zone.id ? 'text-red-500' : 'text-slate-400'}`}>
                  {freeDeliveryEligible ? 'ফ্রি ডেলিভারি' : `৳${zone.charge} চার্জ`}
                </span>
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="bg-white rounded-3xl p-6 flex items-center justify-between border border-slate-100 shadow-sm">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-red-50 text-red-600 rounded-2xl flex items-center justify-center font-black text-xl shadow-inner">৳</div>
          <div>
            <p className="text-xs text-slate-400 font-bold uppercase tracking-wider">সর্বমোট</p>
            <p className="text-3xl font-black text-red-600">৳{total}</p>
          </div>
        </div>
        {freeDeliveryEligible && (
          <div className="bg-green-600/20 text-green-500 px-3 py-1 rounded-full text-[10px] font-black flex items-center gap-1">
            <Truck size={12} /> ফ্রি ডেলিভারি
          </div>
        )}
      </div>

      {stockErrors.length > 0 && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-xl">
          {stockErrors.map((err, i) => (
            <p key={i} className="text-xs text-red-600 font-bold">• {err}</p>
          ))}
        </div>
      )}

      <button
        type="submit"
        disabled={isLoading || stockChecking}
        className="w-full py-5 bg-red-600 hover:bg-red-700 text-white rounded-2xl font-black text-xl flex items-center justify-center gap-3 transition-all shadow-2xl shadow-red-600/40 active:scale-95 disabled:opacity-50"
      >
        {isLoading || stockChecking ? (
          <Loader2 className="animate-spin" size={24} />
        ) : (
          <>অর্ডার সম্পন্ন করুন <CheckCircle size={22} /></>
        )}
      </button>

      <p className="text-[9px] text-slate-500 text-center font-medium">
        * আপনার তথ্য সুরক্ষিত। অর্ডার সম্পন্ন না করলেও আমরা আপনার সাথে যোগাযোগ করতে পারি।
      </p>
    </form>
  );
};

export default InlineOrderForm;