"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import Related from "@/components/related";

export default function ProductDetailClient({ product }) {
  // Client-side interactivity
  const [currentImage, setCurrentImage] = useState(0);
  const [selectedVariant, setSelectedVariant] = useState(0);
  const [currentTab, setCurrentTab] = useState(0);

  const handleDownload = () => {
    // Create a temporary anchor element to trigger PDF download
    const link = document.createElement("a");
    link.href = product.assembly[0];
    link.download = `${product.slug}-assembly-instructions.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <>
      <section className="w-full ">
        <div className="mx-auto max-w-screen-2xl pb-20 pt-5 lg:px-10 lg:pt-16">
          <div className="grid grid-cols-1 gap-10 lg:grid-cols-2">
            {/* Left Section - Images */}
            <div className="relative flex flex-col gap-5 lg:sticky lg:top-[94px] lg:h-fit">
              <div className="flex aspect-square w-full justify-center overflow-hidden bg-white border border-slate-200 sm:aspect-[5/3] lg:rounded-xl">
                <Image src={product.images[currentImage]} priority alt={product.title} width={800} height={800} className="w-full object-contain" />
              </div>
              <div className="grid max-w-[400px] grid-cols-5 gap-2 px-5 sm:px-8 lg:px-0">
                {product.images.map((img, index) => (
                  <button key={index} onClick={() => setCurrentImage(index)}>
                    <Image src={img} alt={`Image ${index + 1}`} width={100} height={100} className={`aspect-square w-full rounded-lg ${currentImage === index ? "border-green-500 border-2" : "border-slate-200 border"} object-contain`} />
                  </button>
                ))}
              </div>
            </div>

            {/* Right Section - Details */}
            <div className="flex flex-col gap-6 px-5 sm:px-8 lg:gap-8 lg:px-0">
              <div className="flex flex-col gap-3">
                {product.isNew && <div className="w-fit h-6 items-center rounded-md bg-green-500 px-2 text-sm text-white sm:flex">New</div>}
                <h1>{product.title}</h1>
                <span className="w-fit shrink-0 rounded-md bg-slate-200 px-3 py-1 text-sm text-slate-500">{product.category}</span>
              </div>

              {/* Variant Selection */}
              <div className="flex flex-col items-start gap-3">
                <span>
                  Color: <span className="font-medium">{product.variants[selectedVariant].color.name}</span>
                </span>
                <div className="flex gap-4 flex-wrap">
                  {product.variants.map((variant, idx) => (
                    <button key={idx} onClick={() => setSelectedVariant(idx)} className={`overflow-hidden rounded-md border-2 ${selectedVariant === idx ? "border-white shadow-md shadow-transparent/20" : "border-transparent"}`}>
                      <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" className="size-8 shrink-0">
                        <path fill={variant.color.top} d="M100 0v100H0L100 0Z" />
                        <path fill={variant.color.bottom} d="M0 0h100L0 100V0Z" />
                        <path stroke="white" strokeWidth="2" d="M100 0 0 100" />
                      </svg>
                    </button>
                  ))}
                </div>
                <div className="text-[10px] opacity-50">SKU: {product.variants[selectedVariant].sku}</div>
              </div>

              {/* Buy Now Button */}
              <Link href={product.buyLink} target="_blank" className="group flex h-12 w-full items-center justify-center gap-2 rounded-lg bg-green-500 px-6 text-base font-medium text-white sm:w-fit">
                Buy Now
              </Link>

              {/* Product Specifications */}
              <div className="flex flex-col gap-1 text-sm">
                <div>Package size: {product.dimension} cm</div>
                <div>Weight: {product.weight} kg</div>
                <button onClick={handleDownload} className="flex mt-2 h-10 w-full items-center justify-center gap-2 rounded-lg border border-slate-300 bg-white px-4 text-sm text-slate-800 transition-colors hover:bg-slate-50 sm:w-fit">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor" className="size-4 shrink-0">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" />
                  </svg>
                  Download Manual
                </button>
              </div>

              {/* Tabs for Features & Description */}
              <div className="flex flex-col gap-6 lg:gap-8">
                <div className="flex gap-6 font-normal">
                  <button onClick={() => setCurrentTab(0)} className={`underline-offset-[10px] ${currentTab === 0 ? "underline font-semibold" : ""}`}>
                    Key Features
                  </button>
                  <button onClick={() => setCurrentTab(1)} className={`underline-offset-[10px] ${currentTab === 1 ? "underline font-semibold" : ""}`}>
                    Description
                  </button>
                </div>

                {currentTab === 0 ? (
                  <div className="text-sm">
                    <ul className="list-disc ml-5">
                      {product.features.map((feature, i) =>
                        feature.includes("<p>") ? (
                          <p key={i} className="mt-4 first:mt-0 text-base font-semibold leading-relaxed">
                            {feature.replace(/<\/?p>/g, "")}
                          </p>
                        ) : (
                          <li key={i} className="leading-relaxed" dangerouslySetInnerHTML={{ __html: feature }} />
                        )
                      )}
                    </ul>
                  </div>
                ) : (
                  <p className="leading-loose text-sm">{product.description}</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>
      <Related />
    </>
  );
}
