import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { X, Loader2 } from 'lucide-react';

export default function EnquiryModal() {
  const [isOpen, setIsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const [successMsg, setSuccessMsg] = useState('');

  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    email: '',
  });

  useEffect(() => {
    // Automatically pop up after 3 seconds
    const timer = setTimeout(() => {
      setIsOpen(true);
    }, 3000);

    const handleOpen = () => setIsOpen(true);
    window.addEventListener('open-enquiry', handleOpen);

    return () => {
      clearTimeout(timer);
      window.removeEventListener('open-enquiry', handleOpen);
    };
  }, []);

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // Only allow digits
    const val = e.target.value.replace(/\D/g, '');
    setFormData({ ...formData, phone: val });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setErrorMsg('');
    setSuccessMsg('');

    try {
      const urlParams = new URLSearchParams(window.location.search);
      const utmSource = urlParams.get('utm_source');
      const utmMedium = urlParams.get('utm_medium');
      const utmValue = [utmSource, utmMedium].filter(Boolean).join('/') || 'Popup Form';
      
      const payload = {
        name: formData.name,
        phone: formData.phone,
        email: formData.email,
        URL: window.location.href,
        sub_sub_source_2fc: utmValue,
        re_enquiry_source_e42: 'Popup Form'
      };

      // Execute webhooks from the client
      const sheetPayload = {
        date: new Date().toISOString(),
        sheetName: "Legacy Kairos",
        name: formData.name || "",
        phone: formData.phone.replace(/\D/g, ''),
        email: formData.email || "",
        source: "Digital",
        sub_source_9ae: "Website",
        sub_sub_source_2fc: payload.sub_sub_source_2fc,
        additional_source__info__dfc: "Legacy Kairos Landing Page",
        re_enquiry_source_e42: payload.re_enquiry_source_e42,
        project_4b930261: "Legacy Kairos",
        project_interest_ebf: "Legacy Kairos",
        URL: payload.URL,
        marketing_agency_177: 'Legacy Lifespaces'
      };

      const searchParams = new URLSearchParams();
      Object.entries(sheetPayload).forEach(([key, value]) => {
        searchParams.append(key, value as string);
      });

      const crmOptions: RequestInit = {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: searchParams.toString()
      };

      const sheetOptions: RequestInit = {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'text/plain' },
        body: JSON.stringify(sheetPayload)
      };

      const { WEBHOOK_CONFIG } = await import('../config');
      const sheetUrl = WEBHOOK_CONFIG.GOOGLE_SHEETS_URL;
      const crmUrl = WEBHOOK_CONFIG.CRM_URL;

      if (sheetUrl) {
        fetch(sheetUrl, sheetOptions).catch(console.error);
      }
      if (crmUrl) {
        fetch(crmUrl, crmOptions).catch(console.error);
      }

      setSuccessMsg('Thank you! Your request has been submitted successfully.');

      try {
        (window as any).dataLayer = (window as any).dataLayer || [];
        (window as any).dataLayer.push({
          'event': 'kairos_landing_page_form_submitted'
        });
        if (typeof (window as any).fbq === 'function') {
          (window as any).fbq('track', 'Lead');
        }
      } catch (err) {}

      setTimeout(() => {
        setIsOpen(false);
        setFormData({ name: '', phone: '', email: '' });
        setSuccessMsg('');
      }, 2000);
    } catch (err: any) {
      setErrorMsg('Something went wrong. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
          <motion.div 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setIsOpen(false)}
            className="absolute inset-0 bg-black/60 backdrop-blur-sm"
          />
          <motion.div 
            initial={{ opacity: 0, scale: 0.95, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 20 }}
            className="relative bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden z-10"
          >
            <div className="bg-primary p-6 text-center relative">
              <button 
                onClick={() => setIsOpen(false)}
                className="absolute top-4 right-4 text-white/80 hover:text-white transition-colors cursor-pointer"
              >
                <X size={24} />
              </button>
              <h3 className="text-2xl font-serif text-white mb-1">Register Your Interest</h3>
              <p className="text-primary-100 text-sm text-white/80">Avail the Best Offers!</p>
            </div>
            <div className="p-6">
              {errorMsg && <div className="mb-4 text-sm text-red-600 bg-red-50 p-3 rounded-lg border border-red-200">{errorMsg}</div>}
              {successMsg && <div className="mb-4 text-sm text-green-600 bg-green-50 p-3 rounded-lg border border-green-200">{successMsg}</div>}

              <form className="space-y-4" onSubmit={handleSubmit}>
                <div>
                  <input type="text" placeholder="Your Name" required className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all text-gray-800" value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} />
                </div>
                <div>
                  <input type="email" placeholder="Email Address" required className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all text-gray-800" value={formData.email} onChange={(e) => setFormData({...formData, email: e.target.value})} />
                </div>
                <div>
                  <input type="tel" placeholder="Phone Number (e.g. 919876543210)" required className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all text-gray-800" value={formData.phone} onChange={handlePhoneChange} />
                </div>
                <button type="submit" disabled={isLoading} className="w-full flex justify-center items-center gap-2 bg-gray-900 hover:bg-primary text-white font-medium py-3 rounded-lg transition-colors mt-2 cursor-pointer disabled:opacity-70 disabled:cursor-not-allowed uppercase tracking-wider">
                  {isLoading ? <Loader2 className="animate-spin" size={20} /> : 'SUBMIT REQUEST'}
                </button>
              </form>
            </div>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
}
