import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { MapPin, Phone, Mail, Globe, Facebook, Instagram, Youtube, Linkedin, Loader2 } from 'lucide-react';

function EnquiryForm() {
  const [isLoading, setIsLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const [successMsg, setSuccessMsg] = useState('');
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    email: '',
  });

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    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 {
      // 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: '',
        additional_source__info__dfc: "Legacy Kairos Landing Page",
        re_enquiry_source_e42: 'Footer Form',
        project_4b930261: "Legacy Kairos",
        project_interest_ebf: "Legacy Kairos",
        URL: window.location.href,
        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(() => {
        setFormData({ name: '', phone: '', email: '' });
        setSuccessMsg('');
      }, 3000);
    } catch (err: any) {
      setErrorMsg('Something went wrong. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-4 w-full">
      {errorMsg && <div className="mb-4 text-sm text-red-400 bg-red-900/40 p-3 rounded-lg border border-red-800">{errorMsg}</div>}
      {successMsg && <div className="mb-4 text-sm text-green-400 bg-green-900/40 p-3 rounded-lg border border-green-800">{successMsg}</div>}

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

export default function Footer() {
  return (
    <footer id="contact" className="bg-gray-900 text-gray-300 pt-20 pb-10">
      <div className="container mx-auto px-4 max-w-7xl">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-12 mb-16">
          <div className="col-span-1 lg:col-span-1">
            <img 
              src="https://raw.githubusercontent.com/erplegacy002-hash/testbalkemal/refs/heads/main/image-removebg-preview%20(4).png" 
              alt="Legacy Lifespaces" 
              className="h-16 mb-6 object-contain"
            />
            <p className="text-sm leading-relaxed mb-6">
              As Pune's most trusted real estate developer, we believe in creating lasting foundations through thoughtful planning, innovative design, and quality craftsmanship.
            </p>
            <div className="flex items-center gap-4 mb-10">
              <a href="https://www.facebook.com/LegacyLifespaces/" target="_blank" rel="noopener noreferrer" className="w-10 h-10 rounded-full bg-gray-800 border border-gray-700 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary hover:-translate-y-1 transition-all duration-300">
                <Facebook size={18} />
              </a>
              <a href="https://www.instagram.com/legacy_lifespaces/" target="_blank" rel="noopener noreferrer" className="w-10 h-10 rounded-full bg-gray-800 border border-gray-700 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary hover:-translate-y-1 transition-all duration-300">
                <Instagram size={18} />
              </a>
              <a href="https://www.youtube.com/@legacylifespaces2148" target="_blank" rel="noopener noreferrer" className="w-10 h-10 rounded-full bg-gray-800 border border-gray-700 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary hover:-translate-y-1 transition-all duration-300">
                <Youtube size={18} />
              </a>
              <a href="https://www.linkedin.com/company/legacylifespaces/" target="_blank" rel="noopener noreferrer" className="w-10 h-10 rounded-full bg-gray-800 border border-gray-700 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary hover:-translate-y-1 transition-all duration-300">
                <Linkedin size={18} />
              </a>
            </div>
            <div className="inline-block bg-gray-800/80 p-5 sm:p-6 rounded-2xl border border-gray-700 w-full sm:w-auto mt-2">
              <div className="flex items-center gap-5 sm:gap-6">
                <img 
                  src="https://raw.githubusercontent.com/erplegacy002-hash/testbalkemal/refs/heads/main/Legacy%20Kairos%20Mahrera%20QR.jpeg" 
                  alt="Legacy Kairos MahaRERA QR Code" 
                  className="w-32 h-32 sm:w-40 sm:h-40 object-contain rounded-xl bg-white p-2 shrink-0 shadow-sm"
                />
                <div className="flex flex-col justify-center">
                  <img 
                    src="https://raw.githubusercontent.com/erplegacy002-hash/testbalkemal/refs/heads/main/maharera-seeklogo.png" 
                    alt="MahaRERA Logo" 
                    className="h-10 sm:h-14 bg-white p-1.5 rounded-lg mb-3 w-fit shadow-sm"
                  />
                  <p className="text-xs sm:text-sm text-gray-400 mb-1 uppercase tracking-wider font-medium">MahaRERA Registration No.</p>
                  <p className="text-xl sm:text-2xl font-bold text-white tracking-wide">P52100047999</p>
                  <a href="https://maharera.mahaonline.gov.in" target="_blank" rel="noopener noreferrer" className="text-xs sm:text-sm text-gray-400 hover:text-white hover:underline mt-1 block transition-colors">maharera.mahaonline.gov.in</a>
                </div>
              </div>
            </div>
          </div>

          <div>
            <h3 className="text-white font-serif text-xl mb-6">Quick Links</h3>
            <ul className="space-y-3 text-sm">
              <li><a href="#overview" className="hover:text-primary transition-colors">Overview</a></li>
              <li><a href="#amenities" className="hover:text-primary transition-colors">Amenities</a></li>
              <li><a href="#gallery" className="hover:text-primary transition-colors">Gallery</a></li>
              <li><a href="#location" className="hover:text-primary transition-colors">Location</a></li>
            </ul>
          </div>

          <div className="col-span-1 lg:col-span-2">
            <div className="bg-gray-800 p-8 rounded-2xl border border-gray-700">
              <h3 className="text-white font-serif text-2xl mb-6">Register your interest</h3>
              <EnquiryForm />
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-8 py-8 border-t border-gray-800">
          <div className="flex items-start gap-4">
            <MapPin className="text-primary shrink-0 mt-1" />
            <p className="text-sm pe-4">
              <a href="https://www.legacylifespaces.com" target="_blank" rel="noopener noreferrer" className="hover:text-primary transition-colors hover:underline">Legacy Lifespaces</a>, Office No. 313, 3rd Floor, Rainbow Plaza, Shivar Chowk, Rahatani, Pune 411017
            </p>
          </div>
          <div className="flex items-start gap-4">
            <Phone className="text-primary shrink-0 mt-1" />
            <p className="text-sm">
              <a href="tel:+918888770022" className="hover:text-primary transition-colors">+91 8888 77 0022</a>
            </p>
          </div>
          <div className="flex flex-col gap-6">
            <div className="flex items-start gap-4">
              <Mail className="text-primary shrink-0 mt-1" />
              <p className="text-sm">
                <a href="mailto:presales@legacylifespaces.com" className="hover:text-primary transition-colors">presales@legacylifespaces.com</a>
              </p>
            </div>
            <div className="flex items-start gap-4">
              <Globe className="text-primary shrink-0 mt-1" />
              <p className="text-sm truncate">
                <a href="https://www.legacylifespaces.com" target="_blank" rel="noopener noreferrer" className="hover:text-primary transition-colors">www.legacylifespaces.com</a>
              </p>
            </div>
          </div>
        </div>

        <div className="text-center pt-8 border-t border-gray-800 text-xs text-gray-500 flex flex-col md:flex-row justify-between items-center gap-4">
          <p>© Copyright 2026. <a href="https://www.legacylifespaces.com" target="_blank" rel="noopener noreferrer" className="hover:text-white transition-colors hover:underline">Legacy Lifespaces</a> LLP | All rights reserved</p>
          <div className="flex flex-wrap gap-4 justify-center md:justify-end">
            <Link to="/terms-and-conditions" className="hover:text-white transition-colors">Terms & Conditions</Link>
            <Link to="/privacy-policy" className="hover:text-white transition-colors">Privacy Policy</Link>
          </div>
        </div>
      </div>
    </footer>
  );
}
