'use client';

import React, { useEffect, useState, useRef } from 'react';
import { useParams, useSearchParams, useRouter } from 'next/navigation';
import api from '@/lib/api';
import { Star, Loader2, Check } from 'lucide-react';
import { trackViewItem, trackBeginCheckout } from '@/lib/analytics';

interface Section {
  id: number;
  block_type: string;
  content: any;
}

interface Product {
  id: number;
  name: string;
  slug: string;
  sku: string;
  price: number;
  sale_price?: number;
  image_url: string;
}

interface LandingPageData {
  id: number;
  title: string;
  slug: string;
  product_id: number;
  landing_price?: number;
  fb_pixel_id?: string;
  template_style: string;
  primary_color: string;
  secondary_color: string;
  gradient_angle: number;
  font_family: string;
  product: Product;
  sections: Section[];
}

export default function LandingPageStorefront() {
  const params = useParams();
  const searchParams = useSearchParams();
  const router = useRouter();
  const slug = params.slug as string;
  const isPreview = searchParams.get('preview') === '1';

  const [pageData, setPageData] = useState<LandingPageData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const checkoutStartedRef = useRef(false);
  const pageViewTrackedRef = useRef(false);

  // Track ViewItem (PageView/ViewContent) when pageData is fetched
  useEffect(() => {
    if (!pageData || pageViewTrackedRef.current) return;
    pageViewTrackedRef.current = true;

    // 1. Track global settings pixel / GA4 / GTM
    trackViewItem(pageData.product);

    // 2. Track landing page specific pixel if present
    if (pageData.fb_pixel_id) {
      const pixelId = pageData.fb_pixel_id.trim();
      if (pixelId) {
        if (typeof window !== 'undefined') {
          // Initialize FB Pixel if it hasn't been initialized
          if (!window.fbq) {
            const fbqTemp = function (...args: any[]) {
              fbqTemp.queue.push(args);
            };
            fbqTemp.queue = [] as any[];
            (fbqTemp as any).loaded = true;
            (fbqTemp as any).version = '2.0';
            (window as any).fbq = fbqTemp;

            const script = document.createElement('script');
            script.async = true;
            script.src = 'https://connect.facebook.net/en_US/fbevents.js';
            document.head.appendChild(script);
          }
          window.fbq('init', pixelId);
          window.fbq('trackSingle', pixelId, 'PageView');
          window.fbq('trackSingle', pixelId, 'ViewContent', {
            content_type: 'product',
            content_ids: [String(pageData.product.id)],
            content_name: pageData.product.name,
            value: Number(pageData.landing_price && Number(pageData.landing_price) > 0 ? pageData.landing_price : (pageData.product.sale_price ?? pageData.product.price)),
            currency: 'BDT'
          });
        }
      }
    }
  }, [pageData]);

  const handleInputChange = () => {
    if (checkoutStartedRef.current || !pageData) return;
    checkoutStartedRef.current = true;

    // 1. Global Begin Checkout (GTM/GA4/Global Pixel)
    const productPrice = Number(pageData.landing_price && Number(pageData.landing_price) > 0 ? pageData.landing_price : (pageData.product.sale_price ?? pageData.product.price));
    trackBeginCheckout([
      {
        product_id: pageData.product.id,
        name: pageData.product.name,
        price: productPrice,
        quantity: quantity,
      }
    ], productPrice * quantity);

    // 2. Custom landing page pixel InitiateCheckout
    if (pageData.fb_pixel_id) {
      const pixelId = pageData.fb_pixel_id.trim();
      if (pixelId && typeof window !== 'undefined' && typeof window.fbq === 'function') {
        window.fbq('trackSingle', pixelId, 'InitiateCheckout', {
          content_type: 'product',
          content_ids: [String(pageData.product.id)],
          value: productPrice * quantity,
          currency: 'BDT'
        });
      }
    }
  };

  // Form Fields
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [shippingArea, setShippingArea] = useState('inside_dhaka');
  const [paymentMethod, setPaymentMethod] = useState('cod');
  const [quantity, setQuantity] = useState(1);
  const [submitting, setSubmitting] = useState(false);

  // Fetch page details
  useEffect(() => {
    async function fetchPage() {
      try {
        const res = await api.get(`/api/landing-pages/${slug}`);
        if (res.data && res.data.success) {
          setPageData(res.data.data);
        } else {
          setError('Landing page not found.');
        }
      } catch (err) {
        console.error(err);
        setError('Landing page could not be loaded.');
      } finally {
        setLoading(false);
      }
    }
    fetchPage();
  }, [slug]);

  // Live Sync Iframe postMessage listener
  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data && event.data.source === 'filament-visual-editor') {
        const updatedFields = event.data.data;
        console.log('Next.js received live update:', updatedFields);
        
        setPageData((prev) => {
          if (!prev) return null;
          
          // Deep clone sections
          const newSections = prev.sections.map(sec => {
            const updatedContent = { ...sec.content };
            
            // Map flattened keys back to their block content
            Object.keys(updatedFields).forEach(key => {
              if (key.startsWith(`sections_builder.${sec.id}.`)) {
                const cleanKey = key.replace(`sections_builder.${sec.id}.`, '');
                updatedContent[cleanKey] = updatedFields[key];
              }
            });
            
            return {
              ...sec,
              content: updatedContent
            };
          });

          return {
            ...prev,
            ...updatedFields,
            sections: newSections
          };
        });
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <Loader2 className="h-8 w-8 animate-spin text-indigo-600" />
      </div>
    );
  }

  if (error || !pageData) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-slate-50 p-6">
        <h1 className="text-xl font-bold text-slate-800 mb-2">404 | Not Found</h1>
        <p className="text-sm text-slate-500">{error || 'This page could not be found.'}</p>
      </div>
    );
  }

  // Dynamic Theme Styling variables
  const themeStyles = {
    '--primary-color': pageData.primary_color,
    '--secondary-color': pageData.secondary_color,
    '--gradient-angle': `${pageData.gradient_angle}deg`,
    '--font-family': pageData.font_family === 'Hind Siliguri' || pageData.font_family === 'Anek Bangla' 
      ? `'${pageData.font_family}', sans-serif`
      : `'Outfit', sans-serif`,
  } as React.CSSProperties;

  // Pricing Calculation
  const activePrice = pageData.landing_price && Number(pageData.landing_price) > 0
    ? Number(pageData.landing_price)
    : (pageData.product.sale_price ?? pageData.product.price);
  
  const shippingCost = shippingArea === 'inside_dhaka' ? 80 : 150;
  const grandTotal = activePrice * quantity + shippingCost;

  // Handle Order Submit
  const handleOrderSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (submitting) return;

    if (!name || !phone || !address) {
      alert('সবগুলো ফিল্ড সঠিকভাবে পূরণ করুন।');
      return;
    }

    setSubmitting(true);
    try {
      const res = await api.post('/api/landing-pages/order', {
        landing_page_id: pageData.id,
        customer_name: name,
        customer_phone: phone,
        shipping_address: address,
        shipping_area: shippingArea,
        payment_method: paymentMethod,
        quantity: quantity,
      });

      if (res.data && res.data.success) {
        const orderId = res.data.order_id;
        const productPrice = Number(pageData.landing_price && Number(pageData.landing_price) > 0 ? pageData.landing_price : (pageData.product.sale_price ?? pageData.product.price));

        // 1. Fire Purchase event on landing-page-specific pixel immediately
        if (pageData.fb_pixel_id) {
          const pixelId = pageData.fb_pixel_id.trim();
          if (pixelId && typeof window !== 'undefined' && typeof window.fbq === 'function') {
            window.fbq('trackSingle', pixelId, 'Purchase', {
              content_type: 'product',
              content_ids: [String(pageData.product.id)],
              value: productPrice * quantity + shippingCost,
              currency: 'BDT'
            });
          }
        }

        // 2. Save order details in sessionStorage for global success page tracking (GTM, GA4, global Meta Pixel)
        const trackingOrder = {
          id: orderId,
          total: productPrice * quantity + shippingCost,
          shipping_fee: shippingCost,
          customer: {
            name: name,
            phone: phone,
            email: '',
          },
          items: [
            {
              product_id: pageData.product.id,
              name: pageData.product.name,
              price: productPrice,
              quantity: quantity,
            }
          ]
        };
        sessionStorage.setItem('last_order_tracking', JSON.stringify(trackingOrder));

        const redirectUrl = res.data.redirect_url;
        if (redirectUrl) {
          window.location.href = redirectUrl;
        } else {
          router.push(`/checkout/success/${orderId}`);
        }
      } else {
        alert(res.data.message || 'অর্ডার করতে ব্যর্থ হয়েছে। আবার চেষ্টা করুন।');
      }
    } catch (err: any) {
      console.error(err);
      alert(err.response?.data?.message || 'অর্ডার সাবমিট করার সময় একটি ত্রুটি ঘটেছে।');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div style={themeStyles} className="bg-slate-50 min-h-screen text-slate-800 antialiased selection:bg-indigo-500 selection:text-white">
      <div style={{ fontFamily: 'var(--font-family)' }}>
        
        {pageData.sections.map((section) => {
          const content = section.content;

          // 1. Hero Block
          if (section.block_type === 'hero') {
            return (
              <section key={section.id} className="relative py-16 lg:py-24 overflow-hidden bg-white border-b border-slate-100">
                <div className="max-w-6xl mx-auto px-6 grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
                  <div className="space-y-6">
                    <h1 className="text-3xl lg:text-5xl font-bold leading-tight text-slate-900">
                      {content.headline || 'প্রিমিয়াম ল্যান্ডিং পেজে স্বাগতম'}
                    </h1>
                    <p className="text-base lg:text-lg text-slate-600 leading-relaxed">
                      {content.subheadline || 'অর্ডার করতে নিচের বোতামে ক্লিক করুন।'}
                    </p>
                    <div>
                      <a 
                        href="#checkout-section" 
                        className="inline-flex items-center justify-center px-8 py-4 rounded-xl font-bold text-lg text-white transition-all shadow-lg hover:shadow-xl hover:translate-y-[-2px]"
                        style={{ background: `linear-gradient(var(--gradient-angle), var(--primary-color), var(--secondary-color))` }}
                      >
                        {content.cta_text || 'অর্ডার করুন'}
                      </a>
                    </div>
                  </div>
                  <div className="flex justify-center relative">
                    <div className="absolute -inset-1 rounded-2xl bg-gradient-to-r from-indigo-500 to-cyan-500 opacity-20 blur-xl"></div>
                    {content.image_path ? (
                      <img 
                        src={`${process.env.NEXT_PUBLIC_API_URL || 'http://sawdabazar.test'}/storage/${content.image_path}`} 
                        alt="Product Hero" 
                        className="relative max-h-[400px] object-contain rounded-2xl shadow-xl border border-slate-150"
                      />
                    ) : (
                      <div className="relative w-full h-[300px] bg-slate-100 rounded-2xl flex items-center justify-center text-slate-400">
                        Product Image Placeholder
                      </div>
                    )}
                  </div>
                </div>
              </section>
            );
          }

          // 2. Features Block
          if (section.block_type === 'features') {
            return (
              <section key={section.id} className="py-16 bg-slate-50 border-b border-slate-150/50">
                <div className="max-w-6xl mx-auto px-6">
                  <h2 className="text-2xl lg:text-4xl font-bold text-center mb-12 text-slate-900">
                    {content.title || 'প্রোডাক্টের বিশেষ সুবিধাসমূহ'}
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                    {content.features_list?.map((feat: any, idx: number) => (
                      <div key={idx} className="p-6 bg-white rounded-2xl border border-slate-200/60 shadow-sm hover:shadow-md transition-all duration-300">
                        <div 
                          className="w-12 h-12 rounded-xl flex items-center justify-center text-white text-xl font-bold mb-4"
                          style={{ background: `linear-gradient(var(--gradient-angle), var(--primary-color), var(--secondary-color))` }}
                        >
                          {idx + 1}
                        </div>
                        <h3 className="text-lg font-bold text-slate-900 mb-2">{feat.title}</h3>
                        <p className="text-sm text-slate-600 leading-relaxed">{feat.description}</p>
                      </div>
                    ))}
                  </div>
                </div>
              </section>
            );
          }

          // 3. Testimonials Block
          if (section.block_type === 'testimonials') {
            return (
              <section key={section.id} className="py-16 bg-white border-b border-slate-100">
                <div className="max-w-5xl mx-auto px-6">
                  <h2 className="text-2xl lg:text-4xl font-bold text-center mb-12 text-slate-900">
                    {content.title || 'আমাদের কাস্টমাররা কী বলছেন'}
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                    {content.testimonials_list?.map((testi: any, idx: number) => (
                      <div key={idx} className="p-6 bg-slate-50 rounded-2xl border border-slate-200/60 relative">
                        <div className="flex gap-0.5 text-yellow-400 mb-3">
                          {Array.from({ length: testi.rating ?? 5 }).map((_, i) => (
                            <Star key={i} className="w-5 h-5 fill-yellow-400 text-yellow-400" />
                          ))}
                        </div>
                        <p className="text-sm text-slate-650 leading-relaxed mb-4 italic">"{testi.feedback}"</p>
                        <div className="flex items-center gap-3">
                          {testi.avatar ? (
                            <img 
                              src={`${process.env.NEXT_PUBLIC_API_URL || 'http://sawdabazar.test'}/storage/${testi.avatar}`} 
                              alt="Avatar" 
                              className="w-10 h-10 rounded-full object-cover"
                            />
                          ) : (
                            <div 
                              className="w-10 h-10 rounded-full flex items-center justify-center text-white text-xs font-bold"
                              style={{ background: `linear-gradient(var(--gradient-angle), var(--primary-color), var(--secondary-color))` }}
                            >
                              {testi.name?.charAt(0)}
                            </div>
                          )}
                          <div>
                            <h4 className="text-sm font-bold text-slate-900">{testi.name}</h4>
                            <span className="text-xs text-slate-400">Verified Buyer</span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </section>
            );
          }

          // 4. Video Embed Block
          if (section.block_type === 'video_embed') {
            const getYoutubeId = (url: string) => {
              const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
              const match = url?.match(regExp);
              return (match && match[2].length === 11) ? match[2] : null;
            };
            const videoId = getYoutubeId(content.video_url);

            return (
              <section key={section.id} className="py-16 bg-slate-50 border-b border-slate-100">
                <div className="max-w-4xl mx-auto px-6 text-center">
                  <h2 className="text-2xl lg:text-4xl font-bold mb-8 text-slate-900">
                    {content.title || 'ভিডিওতে আমাদের প্রোডাক্ট দেখুন'}
                  </h2>
                  <div className="aspect-video bg-black rounded-2xl overflow-hidden shadow-lg border border-slate-200">
                    {videoId ? (
                      <iframe 
                        className="w-full h-full" 
                        src={`https://www.youtube.com/embed/${videoId}`} 
                        frameBorder="0" 
                        allowFullScreen
                      ></iframe>
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-white bg-slate-900">
                        Invalid Video URL
                      </div>
                    )}
                  </div>
                </div>
              </section>
            );
          }

          // 5. FAQ Block
          if (section.block_type === 'faq') {
            return (
              <section key={section.id} className="py-16 bg-white border-b border-slate-100">
                <div className="max-w-3xl mx-auto px-6">
                  <h2 className="text-2xl lg:text-4xl font-bold text-center mb-12 text-slate-900">
                    {content.title || 'সাধারণ কিছু প্রশ্ন ও উত্তর (FAQ)'}
                  </h2>
                  <div className="space-y-4">
                    {content.faqs?.map((faq: any, idx: number) => (
                      <div key={idx} className="border border-slate-200/80 rounded-xl p-5 bg-slate-50">
                        <h3 className="text-base font-bold text-slate-900 mb-2 flex items-center gap-2">
                          <span style={{ color: 'var(--primary-color)' }}>Q.</span> {faq.question}
                        </h3>
                        <p className="text-sm text-slate-600 leading-relaxed pl-6">{faq.answer}</p>
                      </div>
                    ))}
                  </div>
                </div>
              </section>
            );
          }

          // 6. Custom HTML Block
          if (section.block_type === 'custom_html') {
            return (
              <section key={section.id} className="py-8 bg-white">
                <div className="max-w-6xl mx-auto px-6" dangerouslySetInnerHTML={{ __html: content.code || '' }} />
              </section>
            );
          }

          // 7. Express Checkout Form
          if (section.block_type === 'express_checkout') {
            return (
              <section key={section.id} id="checkout-section" className="py-16 bg-slate-50">
                <div className="max-w-xl mx-auto px-6">
                  <div className="bg-white p-8 rounded-2xl border border-slate-200 shadow-xl">
                    <h2 className="text-xl lg:text-2xl font-bold text-center mb-6 text-slate-900">
                      {content.form_title || 'অর্ডার কনফার্ম করতে ফর্মটি পূরণ করুন'}
                    </h2>
                    
                    <form onSubmit={handleOrderSubmit} className="space-y-4">
                      <div>
                        <label className="block text-xs font-bold uppercase text-slate-500 mb-1">আপনার নাম</label>
                        <input 
                          type="text" 
                          value={name}
                          onChange={(e) => setName(e.target.value)}
                          onFocus={handleInputChange}
                          placeholder="এখানে নাম লিখুন" 
                          className="w-full px-4 py-3 rounded-xl border border-slate-250 focus:outline-none focus:border-indigo-500 text-sm" 
                          required 
                        />
                      </div>
                      
                      <div>
                        <label className="block text-xs font-bold uppercase text-slate-500 mb-1">মোবাইল নম্বর</label>
                        <input 
                          type="tel" 
                          value={phone}
                          onChange={(e) => setPhone(e.target.value)}
                          onFocus={handleInputChange}
                          placeholder="১১ ডিজিটের মোবাইল নম্বর" 
                          className="w-full px-4 py-3 rounded-xl border border-slate-250 focus:outline-none focus:border-indigo-500 text-sm" 
                          required 
                        />
                      </div>

                      <div>
                        <label className="block text-xs font-bold uppercase text-slate-500 mb-1">পূর্ণ ঠিকানা</label>
                        <textarea 
                          value={address}
                          onChange={(e) => setAddress(e.target.value)}
                          onFocus={handleInputChange}
                          placeholder="আপনার গ্রাম, থানা ও জেলা লিখুন" 
                          rows={3} 
                          className="w-full px-4 py-3 rounded-xl border border-slate-250 focus:outline-none focus:border-indigo-500 text-sm" 
                          required 
                        />
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-xs font-bold uppercase text-slate-500 mb-1">ডেলিভারি এরিয়া</label>
                          <select 
                            value={shippingArea}
                            onChange={(e) => setShippingArea(e.target.value)}
                            className="w-full px-4 py-3 rounded-xl border border-slate-250 focus:outline-none focus:border-indigo-500 text-sm"
                          >
                            <option value="inside_dhaka">ঢাকার ভিতরে (৳৮০)</option>
                            <option value="outside_dhaka">ঢাকার বাইরে (৳১৫০)</option>
                          </select>
                        </div>

                        <div>
                          <label className="block text-xs font-bold uppercase text-slate-500 mb-1">পরিমাণ (Quantity)</label>
                          <select 
                            value={quantity}
                            onChange={(e) => setQuantity(Number(e.target.value))}
                            className="w-full px-4 py-3 rounded-xl border border-slate-250 focus:outline-none focus:border-indigo-500 text-sm"
                          >
                            <option value="1">১ টি</option>
                            <option value="2">২ টি</option>
                            <option value="3">৩ টি</option>
                            <option value="5">৫ টি</option>
                          </select>
                        </div>
                      </div>

                      <div className="pt-4 border-t border-slate-100 space-y-2">
                        <div className="flex justify-between font-semibold text-slate-800 text-sm">
                          <span>প্রোডাক্টের মূল্য:</span>
                          <span>৳{ (activePrice * quantity).toFixed(2) }</span>
                        </div>
                        <div className="flex justify-between text-slate-500 text-xs">
                          <span>ডেলিভারি চার্জ:</span>
                          <span>৳{ shippingCost.toFixed(2) }</span>
                        </div>
                        <div className="flex justify-between font-bold text-slate-900 text-base pt-2 border-t border-dashed border-slate-100">
                          <span>সর্বমোট মূল্য:</span>
                          <span>৳{ grandTotal.toFixed(2) }</span>
                        </div>

                        <button 
                          type="submit" 
                          disabled={submitting}
                          className="w-full py-4 mt-4 rounded-xl font-bold text-lg text-white shadow-md transition-all flex items-center justify-center gap-2 hover:opacity-95 disabled:opacity-50 cursor-pointer"
                          style={{ background: `linear-gradient(var(--gradient-angle), var(--primary-color), var(--secondary-color))` }}
                        >
                          {submitting ? (
                            <Loader2 className="h-5 w-5 animate-spin" />
                          ) : (
                            content.button_text || 'অর্ডার কনফার্ম করুন'
                          )}
                        </button>
                      </div>
                    </form>
                  </div>
                </div>
              </section>
            );
          }

          return null;
        })}

      </div>
    </div>
  );
}
