'use client';

import { useParams } from 'next/navigation';
import { useState, useEffect, useMemo } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { ChevronLeft, ChevronRight, Maximize2, X, MessageCircle } from 'lucide-react';
import Header from '../../components/Header';
import Footer from '../../components/Footer';
import SizeChart from '../../components/SizeChart';
import PaymentPolicy from '../../components/PaymentPolicy';
import { useCart } from '../../context/CartContext';
import { fetchProductBySlug } from '@/lib/services/products';
import type { FrontendProductSummary } from '@/lib/types';
import { useCurrency, ensureSupportedCurrency } from '../../context/CurrencyContext';
import {
  getMetaContentId,
  trackAddToCart,
  trackViewContent,
} from '@/lib/analytics/meta-pixel';

const DEFAULT_SIZES = ['XS', 'S', 'M', 'ML', 'L', 'XL'] as const;

export default function ProductPage() {
  const params = useParams();
  const productId = params?.id as string | undefined;
  const [product, setProduct] = useState<FrontendProductSummary | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    async function loadProduct() {
      if (!productId) {
        setError('Product Not Found');
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      setError(null);

      try {
        const productData = await fetchProductBySlug(productId);
        if (!isMounted) return;

        if (!productData) {
          setError('Product Not Found');
        }

        setProduct(productData);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Unable to load product');
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadProduct();

    return () => {
      isMounted = false;
    };
  }, [productId]);

  // Cart context
  const { addToCart } = useCart();
  const { formatCurrency } = useCurrency();

  // State management
  const [selectedSize, setSelectedSize] = useState('XS');
  const [quantity, setQuantity] = useState(1);
  const [selectedImage, setSelectedImage] = useState(0);
  const [showCareInstructions, setShowCareInstructions] = useState(true);
  const [showDisclaimer, setShowDisclaimer] = useState(true);
  const [isLightboxOpen, setIsLightboxOpen] = useState(false);
  const [isAddingToCart, setIsAddingToCart] = useState(false);
  const [isSizeChartOpen, setIsSizeChartOpen] = useState(false);
  const [isPaymentPolicyOpen, setIsPaymentPolicyOpen] = useState(false);

  useEffect(() => {
    if (product?.raw.sizes?.length) {
      setSelectedSize(product.raw.sizes[0].size.name);
    }
  }, [product]);

  useEffect(() => {
    if (!product) return;

    const contentId = getMetaContentId(product);
    trackViewContent({
      content_ids: [contentId],
      contents: [{ id: contentId, quantity: 1, item_price: product.price }],
      content_name: product.name,
      content_category: product.primaryCategory ?? undefined,
      value: product.discountPrice ?? product.price,
      currency: ensureSupportedCurrency(product.currency),
    });
  }, [product?.id]);

  const productImages = useMemo(() => {
    if (!product) return [];
    if (product.images.length > 0) {
      return product.images
        .sort((a, b) => a.order - b.order)
        .map((image) => image.url);
    }
    const urls: string[] = [];
    if (product?.image) urls.push(product.image);
    if (product?.hoverImage && product.hoverImage !== product.image) {
      urls.push(product.hoverImage);
    }
    return urls;
  }, [product]);

  const sizeOrder = ['XXS', 'XS', 'S', 'M', 'ML', 'L', 'XL', 'XXL', 'XXXL'];

  const sortSizes = (sizes: string[]) => {
    const uniqueSizes = Array.from(new Set(sizes));
    return uniqueSizes.sort((a, b) => {
      const indexA = sizeOrder.indexOf(a.toUpperCase());
      const indexB = sizeOrder.indexOf(b.toUpperCase());
      if (indexA === -1 && indexB === -1) {
        return a.localeCompare(b);
      }
      if (indexA === -1) return 1;
      if (indexB === -1) return -1;
      return indexA - indexB;
    });
  };

  const sizes = useMemo(() => {
    if (product?.raw.sizes?.length) {
      const extractedSizes = product.raw.sizes.map((item) => item.size.name);
      return sortSizes(extractedSizes);
    }
    return sortSizes([...DEFAULT_SIZES]);
  }, [product]);

  const descriptionHtml = useMemo(() => {
    const description = product?.description ?? product?.shortDescription ?? '';
    if (!description) return '';
    const containsHtml = /<\/?[a-z][\s\S]*>/i.test(description);
    return containsHtml ? description : `<p>${description}</p>`;
  }, [product]);

  // Close lightbox on ESC key and prevent body scroll
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isLightboxOpen) {
        setIsLightboxOpen(false);
      }
    };
    
    if (isLightboxOpen) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', handleEscape);
    } else {
      document.body.style.overflow = 'unset';
    }
    
    return () => {
      window.removeEventListener('keydown', handleEscape);
      document.body.style.overflow = 'unset';
    };
  }, [isLightboxOpen]);

  if (isLoading) {
    return (
      <div className="min-h-screen flex flex-col">
        <Header />
        <main className="grow flex items-center justify-center">
          <p className="text-lg text-gray-500">Loading product...</p>
        </main>
        <Footer />
      </div>
    );
  }

  if (!productId || !product || error) {
    return (
      <div className="min-h-screen flex flex-col">
        <Header />
        <main className="grow flex items-center justify-center">
          <div className="text-center">
            <h1 className="text-4xl font-bold text-gray-900 mb-4">404</h1>
            <p className="text-xl text-gray-600 mb-8">{error ?? 'Product Not Found'}</p>
            <p className="text-sm text-gray-500 mb-8">The page you're looking for doesn't exist.</p>
            <Link href="/" className="bg-black text-white px-6 py-3 inline-block hover:bg-gray-800 transition-colors">
              Return Home
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  const colorName = product.raw.colors?.[0]?.color.name ?? 'As Shown';
  const sku = product.raw.sku ?? 'N/A';
  const primaryCategorySlug = product.primaryCategory ?? 'collections';
  const primaryCategoryLabel = primaryCategorySlug.replace(/-/g, ' ');
  const productCurrency = ensureSupportedCurrency(product.currency);

  const calculateTotalPrice = () => product.price * quantity;

  const handleAddToCart = () => {
    setIsAddingToCart(true);

    addToCart({
      product,
      size: selectedSize,
      fabric: colorName,
      quantity,
      price: product.price * quantity,
    });

    const contentId = getMetaContentId(product);
    trackAddToCart({
      content_ids: [contentId],
      contents: [
        {
          id: contentId,
          quantity,
          item_price: product.price,
        },
      ],
      content_name: product.name,
      content_category: product.primaryCategory ?? undefined,
      value: product.price * quantity,
      currency: productCurrency,
      num_items: quantity,
    });

    setTimeout(() => {
      setIsAddingToCart(false);
    }, 500);
  };

  return (
    <div className="min-h-screen flex flex-col mt-5">
      <Header />
      <main className="grow">
        {/* Breadcrumbs */}
        <div className="border-b border-gray-200 bg-white">
          <div className="container mx-auto px-4 py-3">
            <nav className="text-sm text-gray-600">
              <Link href="/" className="hover:text-gray-900">HOME</Link>
              {' > '}
              <Link href={`/${primaryCategorySlug}`} className="hover:text-gray-900 uppercase">
                {primaryCategoryLabel}
              </Link>
              {' > '}
              <span className="text-gray-900">{product.name.toUpperCase()}</span>
            </nav>
          </div>
        </div>

        <div className="container mx-auto px-4 py-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
            {/* Left Column - Product Images Gallery */}
            <div className="flex flex-col md:flex-row gap-4">
              {/* Image Thumbnails - Left Side */}
              {productImages.length > 1 && (
                <div className="hidden md:flex md:flex-col gap-3 shrink-0">
                  {productImages.map((img, index) => (
                    <button
                      key={index}
                      onClick={() => setSelectedImage(index)}
                      className={`relative w-20 h-20 overflow-hidden border-2 transition-all duration-300 ${
                        selectedImage === index
                          ? 'border-black scale-105'
                          : 'border-gray-300 hover:border-gray-400'
                      }`}
                      aria-label={`Go to image ${index + 1}`}
                    >
                      <Image
                        src={img}
                        alt={`${product.name} thumbnail ${index + 1}`}
                        fill
                        className="object-cover"
                        sizes="80px"
                        loading="lazy"
                        quality={75}
                      />
                    </button>
                  ))}
                </div>
              )}

              {/* Main Image Container */}
              <div className="flex-1 relative">
                <div 
                  className="relative bg-gray-100 aspect-3/4 overflow-hidden group cursor-pointer"
                  onClick={() => setIsLightboxOpen(true)}
                >
                  {/* Image with fade animation */}
                  <div className="relative w-full h-full pointer-events-none">
                    {productImages.map((img, index) => (
                      <div
                        key={index}
                        className={`absolute inset-0 transition-opacity duration-500 ${
                          selectedImage === index ? 'opacity-100 z-10' : 'opacity-0 z-0'
                        }`}
                      >
                        <Image
                          src={img}
                          alt={`${product.name} - view ${index + 1}`}
                          fill
                          className="object-cover"
                          sizes="(max-width: 1024px) 100vw, 50vw"
                          priority={index === 0}
                          loading={index === 0 ? undefined : 'lazy'}
                          quality={index === 0 ? 90 : 85}
                        />
                      </div>
                    ))}
                  </div>
                  
                  {/* Navigation Arrows */}
                  {productImages.length > 1 && (
                    <>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedImage((prev) => (prev === 0 ? productImages.length - 1 : prev - 1));
                        }}
                        className="absolute left-4 top-1/2 -translate-y-1/2 bg-white/90 hover:bg-white p-2 rounded-full shadow-lg transition-all opacity-0 group-hover:opacity-100 z-50 pointer-events-auto"
                        aria-label="Previous image"
                      >
                        <ChevronLeft className="w-6 h-6 text-gray-700" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedImage((prev) => (prev === productImages.length - 1 ? 0 : prev + 1));
                        }}
                        className="absolute right-4 top-1/2 -translate-y-1/2 bg-white/90 hover:bg-white p-2 rounded-full shadow-lg transition-all opacity-0 group-hover:opacity-100 z-50 pointer-events-auto"
                        aria-label="Next image"
                      >
                        <ChevronRight className="w-6 h-6 text-gray-700" />
                      </button>
                    </>
                  )}

                  {/* Zoom Button */}
                  <button 
                    onClick={(e) => {
                      e.stopPropagation();
                      setIsLightboxOpen(true);
                    }}
                    className="absolute bottom-4 right-4 bg-white p-2 rounded shadow-lg hover:bg-gray-50 transition-colors z-20"
                  >
                    <Maximize2 className="w-5 h-5 text-gray-700" />
                  </button>


                  {/* Image Counter */}
                  {productImages.length > 1 && (
                    <div className="absolute top-4 left-4 bg-black/60 text-white px-3 py-1 rounded text-sm z-20">
                      {selectedImage + 1} / {productImages.length}
                    </div>
                  )}
                </div>
              </div>

              {/* Mobile Thumbnails */}
              {productImages.length > 1 && (
                <div className="md:hidden mt-4 flex justify-center gap-2 overflow-x-auto">
                  {productImages.map((img, index) => (
                    <button
                      key={`mobile-thumb-${index}`}
                      onClick={() => setSelectedImage(index)}
                      className={`relative w-20 h-20 shrink-0 overflow-hidden border-2 transition-all duration-300 ${
                        selectedImage === index
                          ? 'border-black'
                          : 'border-gray-300 hover:border-gray-400'
                      }`}
                      aria-label={`Go to image ${index + 1}`}
                    >
                      <Image
                        src={img}
                        alt={`${product.name} thumbnail ${index + 1}`}
                        fill
                        className="object-cover"
                        sizes="80px"
                        loading="lazy"
                        quality={75}
                      />
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Right Column - Product Summary */}
            <div className="space-y-8">
              <div className="space-y-4">
                <h1 className="text-3xl font-semibold tracking-wide text-gray-900">{product.name}</h1>
                <div className="text-2xl font-bold text-gray-900">
                  {formatCurrency(product.price, { fromCurrency: productCurrency })}
                </div>
              </div>

              {/* Size Selection */}
              <div className="space-y-3">
                <label className="block text-sm font-semibold text-gray-900 mb-3">SIZE</label>
                <div className="flex flex-wrap gap-2">
                  {sizes.map((size) => (
                    <button
                      key={size}
                      onClick={() => setSelectedSize(size)}
                      className={`px-3 py-2 border-2 font-medium transition-colors text-sm ${
                        selectedSize === size
                          ? 'border-black bg-black text-white'
                          : 'border-gray-300 text-gray-700 hover:border-gray-400'
                      }`}
                    >
                      {size}
                    </button>
                  ))}
                </div>
              </div>

              {/* Short Description */}
              <div className="space-y-2">
                {/* <h2 className="text-sm font-semibold text-gray-900 uppercase tracking-wide">Description</h2> */}
                <p className="text-md leading-relaxed text-gray-700">
                  {product.shortDescription ?? 'Embellished craftsmanship with timeless detailing.'}
                </p>
                {/* <div className="text-md text-gray-600 space-y-1">
                  <p><strong className="text-black">SKU:</strong> {sku}</p>
                  <p><strong className="text-black">Color:</strong> {colorName}</p>
                  <p><strong className="text-black">Fabric:</strong> {product.raw?.colors?.[0]?.color.name ?? 'As shown'}</p>
                </div> */}
              </div>

              {/* Size Guide Button */}
              <div className="space-y-2">
                <button
                  onClick={() => setIsSizeChartOpen(true)}
                  className="flex items-center gap-2 text-sm text-gray-700 hover:text-gray-900 transition-colors"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                  </svg>
                  VIEW THE SIZE GUIDE
                </button>
                <button
                  onClick={() => setIsPaymentPolicyOpen(true)}
                  className="flex items-center gap-2 text-sm text-gray-700 hover:text-gray-900 transition-colors"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                  </svg>
                  PAYMENT POLICY
                </button>
              </div>

              {/* Quantity & Add to Cart */}
              <div className="flex flex-col gap-4">
                {/* Quantity Section */}
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-semibold text-gray-900">QUANTITY</label>
                  <div className="flex items-center gap-3">
                    <div className="flex items-center border border-black">
                      <button
                        onClick={() => setQuantity(Math.max(1, quantity - 1))}
                        className="w-10 h-12 flex items-center justify-center text-lg font-semibold text-gray-900 hover:bg-gray-50 transition-colors"
                        type="button"
                      >
                        −
                      </button>
                      <input
                        type="number"
                        value={quantity}
                        onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
                        className="w-16 h-12 text-center border-x border-black focus:outline-none focus:ring-0"
                        min="1"
                      />
                      <button
                        onClick={() => setQuantity(quantity + 1)}
                        className="w-10 h-12 flex items-center justify-center text-lg font-semibold text-gray-900 hover:bg-gray-50 transition-colors"
                        type="button"
                      >
                        +
                      </button>
                    </div>
                    <span className="text-base font-semibold text-gray-900">
                      Total: {formatCurrency(calculateTotalPrice(), { fromCurrency: productCurrency })}
                    </span>
                  </div>
                </div>

                {/* Add to Cart Button */}
                <button 
                  onClick={handleAddToCart}
                  disabled={isAddingToCart}
                  className={`flex-1 bg-black text-white px-8 py-3 font-semibold hover:bg-gray-800 transition-colors uppercase ${
                    isAddingToCart ? 'opacity-75 cursor-not-allowed' : ''
                  }`}
                >
                  {isAddingToCart ? 'ADDING...' : 'ADD TO CART'}
                </button>

                {/* WhatsApp Fashion Consultant Button */}
                <a
                  href={`https://wa.me/${+923058165000}?text=${encodeURIComponent('Hello! I need assistance with Bakht Apparel.')}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center justify-center gap-2 bg-[#25D366] px-4 py-3 text-sm font-semibold text-white shadow-lg transition-transform hover:scale-105 hover:bg-[#1eb255]"
                  aria-label="Chat on WhatsApp"
                >
                  <div className="relative h-5 w-5">
                    <Image src="/assets/whatsapp.png" alt="WhatsApp" fill className="object-contain" />
                  </div>
                  Chat with fashion consultant
                </a>

               
              </div>
            
             
            </div>
          </div>
          <div className="mt-12 lg:mt-16">
            <div className="grid grid-cols-1 lg:grid-cols-1 gap-12">
              <div className="space-y-6 lg:col-start-1">
                <h2 className="text-lg font-semibold text-gray-900 tracking-wide uppercase">Product Description</h2>
                {descriptionHtml ? (
                  <div
                    className="prose prose-sm max-w-none text-gray-900 leading-relaxed [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5"
                    dangerouslySetInnerHTML={{ __html: descriptionHtml }}
                  />
                ) : (
                  <p className="text-sm leading-relaxed text-gray-700">
                    {product.shortDescription ?? 'Details coming soon.'}
                  </p>
                )}
              </div>
            </div>
          </div>
           {/* Delivery Time */}
        

              {/* Care Instructions */}
              <div className="border-t border-gray-200 pt-4">
                <button
                  onClick={() => setShowCareInstructions(!showCareInstructions)}
                  className="flex items-center justify-between w-full text-left"
                >
                  <span className="text-sm font-semibold text-gray-900">CARE INSTRUCTIONS</span>
                  {showCareInstructions ? (
                    <span className="text-2xl text-gray-400">−</span>
                  ) : (
                    <span className="text-2xl text-gray-400">+</span>
                  )}
                </button>
                <div
                  className={`overflow-hidden transition-all duration-300 ease-in-out ${
                    showCareInstructions ? 'max-h-96 opacity-100' : 'max-h-0 opacity-0'
                  }`}
                >
                  <div className="mt-4 text-sm text-gray-600 space-y-2">
                    <p>• Dry clean only</p>
                    <p>• Do not bleach</p>
                    <p>• Iron on low heat</p>
                    <p>• Store in a cool, dry place</p>
                    <p>• Handle with care to preserve embellishments</p>
                  </div>
                </div>
              </div>

              {/* Disclaimer */}
              <div className="border-t border-gray-200 pt-4">
                <button
                  onClick={() => setShowDisclaimer(!showDisclaimer)}
                  className="flex items-center justify-between w-full text-left"
                >
                  <span className="text-sm font-semibold text-gray-900">DISCLAIMER</span>
                  {showDisclaimer ? (
                    <span className="text-2xl text-gray-400">−</span>
                  ) : (
                    <span className="text-2xl text-gray-400">+</span>
                  )}
                </button>
                <div
                  className={`overflow-hidden transition-all duration-300 ease-in-out ${
                    showDisclaimer ? 'max-h-96 opacity-100' : 'max-h-0 opacity-0'
                  }`}
                >
                  <div className="mt-4 text-sm text-gray-600">
                    <p>
                      Colors may vary slightly due to monitor settings. All measurements are approximate. 
                      Please refer to the size guide for accurate sizing information.
                    </p>
                  </div>
                </div>
              </div>
         
        </div>
      </main>
      <Footer />

      {/* Lightbox Modal */}
      {isLightboxOpen && (
        <div 
          className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
          onClick={() => setIsLightboxOpen(false)}
        >
          {/* Close Button */}
          <button
            onClick={() => setIsLightboxOpen(false)}
            className="absolute top-4 right-4 bg-white/10 hover:bg-white/20 text-white p-2 rounded-full transition-colors z-10"
            aria-label="Close lightbox"
          >
            <X className="w-6 h-6" />
          </button>

          {/* Image Container */}
          <div 
            className="relative max-w-7xl max-h-[90vh] w-full h-full flex items-center justify-center"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Image with fade animation */}
            <div className="relative w-full h-full">
              {productImages.map((img, index) => (
                <div
                  key={index}
                  className={`absolute inset-0 transition-opacity duration-500 flex items-center justify-center ${
                    selectedImage === index ? 'opacity-100 z-10' : 'opacity-0 z-0'
                  }`}
                >
                  <div className="relative w-full h-full max-w-5xl max-h-[90vh]">
                    <Image
                      src={img}
                      alt={`${product.name} - view ${index + 1}`}
                      fill
                      className="object-contain"
                      sizes="100vw"
                      quality={90}
                      priority={index === selectedImage}
                    />
                  </div>
                </div>
              ))}
            </div>

            {/* Navigation Arrows */}
            {productImages.length > 1 && (
              <>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    setSelectedImage((prev) => (prev === 0 ? productImages.length - 1 : prev - 1));
                  }}
                  className="absolute left-4 top-1/2 -translate-y-1/2 bg-white/20 hover:bg-white/30 text-white p-3 rounded-full transition-all z-20"
                  aria-label="Previous image"
                >
                  <ChevronLeft className="w-8 h-8" />
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    setSelectedImage((prev) => (prev === productImages.length - 1 ? 0 : prev + 1));
                  }}
                  className="absolute right-4 top-1/2 -translate-y-1/2 bg-white/20 hover:bg-white/30 text-white p-3 rounded-full transition-all z-20"
                  aria-label="Next image"
                >
                  <ChevronRight className="w-8 h-8" />
                </button>
              </>
            )}

            {/* Image Counter */}
            {productImages.length > 1 && (
              <div className="absolute bottom-4 left-1/2 -translate-x-1/2 bg-black/60 text-white px-4 py-2 rounded text-sm z-20">
                {selectedImage + 1} / {productImages.length}
              </div>
            )}

          </div>
        </div>
      )}

      {/* Size Chart Popup */}
      <SizeChart isOpen={isSizeChartOpen} onClose={() => setIsSizeChartOpen(false)} />
      
      {/* Payment Policy Popup */}
      <PaymentPolicy isOpen={isPaymentPolicyOpen} onClose={() => setIsPaymentPolicyOpen(false)} />
    </div>
  );
}
