"use client";

import Image from "next/image";
import DataLink from "@/components/common/DataLink";
import InnerImageZoom from "react-inner-image-zoom";
import "react-inner-image-zoom/lib/styles.min.css";
import { useRouter } from "next/navigation";
import {
  useCallback,
  useMemo,
  useState,
  useSyncExternalStore,
  type MouseEvent,
} from "react";
import { toast } from "sonner";
import type { ProductDetailContent } from "@/data/product-detail-main";
import { shopAssets } from "@/data/shop";
import {
  addProductQuantityToCart,
  getProductCartQuantity,
  setProductCartQuantity,
  subscribeCartChanges,
} from "@/lib/cart-add";

const STAR_SIZE = 16;
const THUMB = 88;
const ZOOM_MAIN = 600;
const QTY_MIN = 1;
const QTY_MAX = 99;
const CHECK = "/assets/images/icon/check1-2.svg";

type ProductSliderProps = {
  detail: ProductDetailContent;
};

export default function ProductSlider({ detail }: ProductSliderProps) {
  const router = useRouter();
  const product = detail.product;
  const slides = detail.gallery;

  const [activeIndex, setActiveIndex] = useState(0);
  const cartQuantity = useSyncExternalStore(
    subscribeCartChanges,
    () => getProductCartQuantity(product.id),
    () => 0,
  );
  const [quantity, setQuantity] = useState(() =>
    cartQuantity > 0 ? cartQuantity : QTY_MIN,
  );
  const isAddedToCart = cartQuantity > 0;

  const activeSlide = slides[activeIndex] ?? slides[0];

  const bumpQty = useCallback((delta: number) => {
    setQuantity((q) => Math.min(QTY_MAX, Math.max(QTY_MIN, q + delta)));
  }, []);

  const onQtyChange = useCallback((raw: string) => {
    const digits = raw.replace(/\D/g, "");
    if (digits === "") {
      setQuantity(QTY_MIN);
      return;
    }
    setQuantity(
      Math.min(QTY_MAX, Math.max(QTY_MIN, Number.parseInt(digits, 10))),
    );
  }, []);

  const onAddToCart = useCallback(
    (e: MouseEvent<HTMLAnchorElement | HTMLButtonElement>) => {
      e.preventDefault();
      addProductQuantityToCart(product.id, quantity);
      toast.success(`${product.title} added to cart`, {
        description: `Added ${quantity} item${quantity === 1 ? "" : "s"} to your cart.`,
        action: {
          label: "View cart",
          onClick: () => router.push("/cart"),
        },
      });
    },
    [product.id, product.title, quantity, router],
  );

  const onViewCart = useCallback(
    (e: MouseEvent<HTMLAnchorElement | HTMLButtonElement>) => {
      e.preventDefault();
      if (quantity !== cartQuantity) {
        setProductCartQuantity(product.id, quantity);
      }
      router.push("/cart");
    },
    [cartQuantity, product.id, quantity, router],
  );

  const stars = useMemo(
    () => Array.from({ length: product.rating }, (_, i) => i),
    [product.rating],
  );

  return (
    <>
      <div className="col-lg-6">
        <div className="product-slider">
          <div className="gallery">
            <div className="main-image" id="main-image">
              <InnerImageZoom
                key={activeSlide.id}
                src={activeSlide.largeSrc}
                zoomSrc={activeSlide.largeSrc}
                zoomType="hover"
                zoomScale={2.5}
                hideHint
                width={ZOOM_MAIN}
                height={ZOOM_MAIN}
                className="w-100"
                imgAttributes={{
                  alt: activeSlide.alt,
                  id: "current",
                }}
              />
            </div>
            <div className="thumbnails" id="thumbnails">
              {slides.map((slide, index) => (
                <button
                  key={slide.id}
                  type="button"
                  className={`p-0 ${index === activeIndex ? "active" : ""}`}
                  aria-label={`Show image ${index + 1}`}
                  aria-current={index === activeIndex ? "true" : undefined}
                  onClick={() => setActiveIndex(index)}
                >
                  <Image
                    src={slide.thumbSrc}
                    alt={slide.alt}
                    width={THUMB}
                    height={THUMB}
                    data-large={slide.largeSrc}
                  />
                </button>
              ))}
            </div>
          </div>
          <div className="lightbox" id="lightbox">
            <span className="close-lightbox" id="close">
              ×
            </span>
            <div className="lightbox-content">
              <div className="arrow arrow-left" id="light-prev">
                ❮
              </div>
              <Image
                id="lightbox-img"
                src={activeSlide.largeSrc}
                alt="Lightbox preview"
                width={900}
                height={900}
                style={{ width: "auto", height: "auto" }}
              />
              <div className="arrow arrow-right" id="light-next">
                ❯
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="col-lg-6">
        <div
          className="product-detail-content"
          data-aos="fade-left"
          data-aos-duration={900}
          data-aos-delay={300}
        >
          {product.onSale ? <span className="sales">Sale!</span> : null}
          <h2 className="title">{product.title}</h2>
          <div className="product-rating">
            <ul className="rating-area">
              {stars.map((i) => (
                <li key={i}>
                  <Image
                    src={shopAssets.ratingIcon}
                    alt="Star Rating"
                    width={STAR_SIZE}
                    height={STAR_SIZE}
                  />
                </li>
              ))}
            </ul>
            <span>{detail.meta.reviewsText}</span>
          </div>
          <span className="price3">
            {product.compareAtPrice ? (
              <del>{product.compareAtPrice}</del>
            ) : null}
            {product.price}
          </span>
          {detail.paragraphs.map((text, i) => (
            <p key={i}>{text}</p>
          ))}
          <ul className="digital-list">
            {detail.bullets.map((b) => (
              <li key={b.id}>
                <Image src={CHECK} alt="Check Icon" width={18} height={18} />
                {b.text}
              </li>
            ))}
          </ul>
          <div className="cart-btn-box2">
            <div className="qty-box">
              <button
                type="button"
                className="qty-btn minus"
                aria-label="Decrease quantity"
                onClick={() => bumpQty(-1)}
              >
                -
              </button>
              <input
                type="text"
                inputMode="numeric"
                className="qty-input"
                value={quantity}
                aria-label="Quantity"
                onChange={(e) => onQtyChange(e.target.value)}
              />
              <button
                type="button"
                className="qty-btn plus"
                aria-label="Increase quantity"
                onClick={() => bumpQty(1)}
              >
                +
              </button>
            </div>
            {isAddedToCart ? (
              <DataLink
                href="/cart"
                className="btn-style1"
                onClick={onViewCart}
              >
                View Cart
                <span>
                  <Image
                    src={shopAssets.arrowIcon}
                    alt="Arrow Icon for View Cart"
                    width={14}
                    height={14}
                  />
                </span>
              </DataLink>
            ) : (
              <DataLink href="#" className="btn-style1" onClick={onAddToCart}>
                Add to Cart
                <span>
                  <Image
                    src={shopAssets.arrowIcon}
                    alt="Arrow Icon for Add to Cart"
                    width={14}
                    height={14}
                  />
                </span>
              </DataLink>
            )}
          </div>
          <ul className="detail-list">
            <li>
              <span>SKU:</span>
              {detail.meta.sku}
            </li>
            <li>
              <span>Categories:</span>
              {detail.meta.categoriesLabel}
            </li>
            <li>
              <span>Tags:</span>
              {detail.meta.tagsLabel}
            </li>
          </ul>
        </div>
      </div>
    </>
  );
}
