"use client";

import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { Facebook, Instagram, PlayCircle } from "lucide-react";
import Link from "next/link";
import { useSettings } from "@/context/SettingsContext";
import { FaXTwitter } from "react-icons/fa6";

export default function SingleProductView({ product }) {
  const { settings } = useSettings();
  const [open, setOpen] = useState(false);
  const containerRef = useRef(null);

  // Close menu on outside click
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target)
      ) {
        setOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const rawImages =
    product.product_image?.split(",").map((img) => img.trim()) || [];
  const images = [...rawImages.map((img) => ({ type: "image", src: img }))];

  // Robust video ID extraction
  function extractYouTubeVideoId(url) {
    const regex =
      /(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
    const match = url.match(regex);
    return match ? match[1] : null;
  }

  // Add video as last "image"
  if (product.video_url) {
    const videoId = extractYouTubeVideoId(product.video_url);
    if (videoId) {
      images.push({
        type: "video",
        src: `https://www.youtube.com/watch?v=${videoId}`,
        thumbnail: `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`,
      });
    }
  }

  const [activeImage, setActiveImage] = useState(images[0]);
  const [currentUrl, setCurrentUrl] = useState("");

  useEffect(() => {
    if (typeof window !== "undefined") {
      setCurrentUrl(window.location.href);
    }
  }, []);

  // Construct WhatsApp URL logic here for cleaner JSX
  const whatsappUrl = `https://api.whatsapp.com/send?phone=${
    settings.mobile
  }&text=${encodeURIComponent(
    `Hello Sir,\n\nI am interested in your product: ${product.name}.\nPlease find the product link below:\n${currentUrl}\n\nThank you!`,
  )}`;

  return (
    <div className="w-full min-h-screen bg-white">
      <div className="max-w-[1400px] mx-auto px-4 py-12 lg:px-12 lg:py-20">
        <div className="flex flex-col lg:flex-row gap-12 lg:gap-20">
          {/* Left: Main Viewer & Thumbnails */}
          <div className="w-full lg:w-3/5 flex flex-col items-center">
            {/* Main Image Frame - Jewelry Box Style */}
            <div className="w-full aspect-square relative overflow-hidden bg-stone-50 border border-stone-100 shadow-sm transition-shadow duration-500 hover:shadow-lg rounded-sm group">
              {activeImage.type === "image" ? (
                <div
                  onMouseMove={(e) => {
                    const rect = e.currentTarget.getBoundingClientRect();
                    const x = ((e.clientX - rect.left) / rect.width) * 100;
                    const y = ((e.clientY - rect.top) / rect.height) * 100;
                    e.currentTarget.style.backgroundPosition = `${x}% ${y}%`;
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundSize = "cover";
                    e.currentTarget.style.backgroundPosition = "center";
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundSize = "200%";
                  }}
                  style={{
                    backgroundImage: `url(${encodeURI(
                      activeImage.src?.replace("/api", ""),
                    )})`,
                    backgroundSize: "cover",
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: "center",
                    transition:
                      "background-size 0.4s ease-out, background-position 0.1s ease",
                  }}
                  className="w-full h-full relative cursor-crosshair"
                >
                  <Image
                    src={encodeURI(activeImage.src)?.replace("/api", "")}
                    alt={product?.name}
                    fill
                    sizes="(max-width: 768px) 100vw, 50vw"
                    className="object-contain opacity-0 w-full h-full"
                    priority
                  />
                </div>
              ) : (
                <iframe
                  src={activeImage.src.replace("watch?v=", "embed/")}
                  className="w-full h-full aspect-video"
                  frameBorder="0"
                  allowFullScreen
                ></iframe>
              )}

              {/* OLD WHATSAPP BUTTON REMOVED FROM HERE */}
            </div>

            {/* Thumbnails - Elegant Strip */}
            <div className="w-full mt-8">
              <div className="flex gap-4 overflow-x-auto pb-4 scrollbar-hide justify-center lg:justify-start">
                {images.map((item, index) => (
                  <button
                    key={index}
                    onClick={() => setActiveImage(item)}
                    className={`relative w-20 h-20 lg:w-24 lg:h-24 shrink-0 transition-all duration-300 ease-in-out border ${
                      activeImage.src === item.src
                        ? "border-brand-gold opacity-100 ring-1 ring-brand-gold ring-offset-2"
                        : "border-stone-200 opacity-60 hover:opacity-100 hover:border-stone-400"
                    }`}
                  >
                    <Image
                      src={
                        item.type === "video"
                          ? item.thumbnail
                          : item.src?.replace("/api", "")
                      }
                      alt={`thumb-${index}`}
                      fill
                      className="object-cover"
                    />

                    {item.type === "video" && (
                      <div className="absolute inset-0 flex items-center justify-center bg-black/20">
                        <PlayCircle className="w-8 h-8 text-white drop-shadow-md" />
                      </div>
                    )}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Right: Details Panel */}
          <div className="w-full lg:w-2/5 flex flex-col justify-start pt-2">
            {/* Category Breadcrumb */}
            <div className="mb-4">
              <span className="text-xs font-lato uppercase tracking-[0.2em] text-brand-gold font-bold">
                {product.category_name || "Collection"}
              </span>
            </div>

            {/* Product Title Row with WhatsApp Button */}
            <div className="flex flex-row justify-between items-start gap-4 mb-8">
              <h1 className="text-3xl lg:text-4xl font-cormorant text-brand-dark font-medium leading-tight">
                {product.name}
              </h1>

              {/* New WhatsApp Enquiry Button */}
              <Link
                href={whatsappUrl}
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Share on WhatsApp"
                className="shrink-0"
              >
                <div className="group flex items-center gap-2 px-4 py-2 border border-[#25D366] rounded-sm hover:bg-[#25D366] transition-all duration-300 cursor-pointer">
                  <WhatsAppIcon
                    className="w-5 h-5 group-hover:fill-white transition-colors duration-300"
                    color="#25D366" // Start Green
                  />
                  <span className="hidden sm:block text-xs font-bold uppercase tracking-widest text-[#25D366] group-hover:text-white transition-colors duration-300">
                    Enquire
                  </span>
                </div>
              </Link>
            </div>

            {/* Divider */}
            <div className="w-16 h-[1px] bg-stone-300 mb-8"></div>

            {/* Description */}
            <div className="mb-10">
              <h3 className="text-sm font-lato uppercase tracking-widest text-stone-900 mb-4">
                Description
              </h3>
              <p className="text-stone-600 font-lato leading-relaxed text-base lg:text-lg font-light">
                {product.description || "No description provided."}
              </p>
            </div>

            {/* Share Section - Minimalist & Elegant */}
            <div className="mt-auto border-t border-stone-100 pt-8">
              <div className="flex items-center gap-4">
                <span className="sm:text-sm font-cormorant italic text-stone-500 text-lg">
                  Share this piece :
                </span>

                <div className="flex gap-3">
                  <Link
                    href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(
                      currentUrl,
                    )}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-full border border-stone-200 flex items-center justify-center text-stone-500 hover:bg-brand-dark hover:border-brand-dark hover:text-white transition-all duration-300"
                  >
                    <Facebook className="w-4 h-4" />
                  </Link>

                  <Link
                    href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(
                      currentUrl,
                    )}&text=${encodeURIComponent(
                      product.name,
                    )} - Selvakumar Jewellery`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-full border border-stone-200 flex items-center justify-center text-stone-500 hover:bg-brand-dark hover:border-brand-dark hover:text-white transition-all duration-300"
                  >
                    <FaXTwitter className="w-4 h-4" />
                  </Link>

                  {settings?.social_links?.find(
                    (s) => s.platform === "instagram",
                  ) && (
                    <Link
                      href={
                        settings.social_links.find(
                          (s) => s.platform === "instagram",
                        )?.url
                      }
                      target="_blank"
                      rel="noopener noreferrer"
                      className="w-10 h-10 rounded-full border border-stone-200 flex items-center justify-center text-stone-500 hover:bg-brand-dark hover:border-brand-dark hover:text-white transition-all duration-300"
                    >
                      <Instagram className="w-4 h-4" />
                    </Link>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// components/WhatsAppIcon.js
export function WhatsAppIcon({ size = 20, color = "#25D366", className = "" }) {
  return (
    <svg
      className={className}
      width={size}
      height={size}
      viewBox="0 0 32 32"
      xmlns="http://www.w3.org/2000/svg"
      fill={color}
    >
      <path d="M16 .002C7.163.002.002 7.163.002 16c0 2.82.737 5.532 2.137 7.94L0 32l8.31-2.13A15.931 15.931 0 0016 32c8.837 0 16-7.163 16-16S24.837.002 16 .002zm0 29.066a13.03 13.03 0 01-6.594-1.808l-.473-.28-4.933 1.265 1.31-4.81-.308-.495A12.934 12.934 0 012.934 16c0-7.256 5.809-13.066 13.066-13.066S29.066 8.744 29.066 16 23.257 29.068 16 29.068z" />
      <path d="M24.095 19.92c-.363-.182-2.15-1.065-2.483-1.188-.333-.121-.575-.182-.817.183-.242.364-.94 1.187-1.152 1.43-.212.243-.394.273-.757.091-.364-.182-1.538-.567-2.93-1.808-1.084-.968-1.813-2.166-2.026-2.53-.212-.364-.023-.56.16-.742.165-.164.364-.425.546-.637.182-.212.242-.364.364-.606.121-.243.061-.455-.03-.637-.091-.182-.817-1.973-1.12-2.697-.295-.71-.597-.612-.817-.623l-.696-.012c-.242 0-.637.091-.97.455s-1.27 1.242-1.27 3.03 1.3 3.513 1.48 3.757c.182.243 2.552 3.91 6.188 5.487.864.372 1.536.595 2.06.76.864.273 1.65.234 2.27.142.692-.104 2.15-.878 2.453-1.723.303-.848.303-1.576.212-1.723-.09-.147-.333-.242-.696-.424z" />
    </svg>
  );
}
