"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import { formatPrice, type Product } from "@/data/products";

type ProductModalProps = {
  product: Product;
  onClose: () => void;
};

export function ProductModal({ product, onClose }: ProductModalProps) {
  const [activeImage, setActiveImage] = useState(0);
  const images = product.images.length > 0 ? product.images : ["/product-placeholder.svg"];
  const hasMultiple = images.length > 1;

  useEffect(() => {
    setActiveImage(0);
  }, [product.id]);

  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
      if (!hasMultiple) return;
      if (event.key === "ArrowLeft") {
        setActiveImage((index) => (index + 1) % images.length);
      }
      if (event.key === "ArrowRight") {
        setActiveImage((index) => (index - 1 + images.length) % images.length);
      }
    };

    document.addEventListener("keydown", onKeyDown);
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = previousOverflow;
    };
  }, [hasMultiple, images.length, onClose]);

  const showPrev = () => {
    setActiveImage((index) => (index - 1 + images.length) % images.length);
  };

  const showNext = () => {
    setActiveImage((index) => (index + 1) % images.length);
  };

  return (
    <div className="product-modal" role="presentation">
      <div className="product-modal__backdrop" onClick={onClose} />
      <div
        className="product-modal__dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="product-modal-title"
      >
        <button
          type="button"
          className="product-modal__close"
          onClick={onClose}
          aria-label="بستن"
        >
          <svg viewBox="0 0 24 24" aria-hidden="true">
            <path
              d="M6 6l12 12M18 6L6 18"
              fill="none"
              stroke="currentColor"
              strokeWidth="2.2"
              strokeLinecap="round"
            />
          </svg>
        </button>

        <div className="product-modal__gallery">
          <div className="product-modal__media">
            <Image
              src={images[activeImage]}
              alt={product.name}
              width={640}
              height={640}
              sizes="(max-width: 504px) 90vw, 420px"
              priority
            />
          </div>

          {hasMultiple ? (
            <>
              <button
                type="button"
                className="product-modal__nav product-modal__nav--prev"
                onClick={showPrev}
                aria-label="تصویر قبلی"
              >
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path
                    d="M9 5l7 7-7 7"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2.2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </button>
              <button
                type="button"
                className="product-modal__nav product-modal__nav--next"
                onClick={showNext}
                aria-label="تصویر بعدی"
              >
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path
                    d="M15 5l-7 7 7 7"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2.2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </button>
              <div className="product-modal__dots" role="tablist" aria-label="تصاویر محصول">
                {images.map((image, index) => (
                  <button
                    key={`${image}-${index}`}
                    type="button"
                    role="tab"
                    aria-selected={index === activeImage}
                    className={`product-modal__dot${index === activeImage ? " is-active" : ""}`}
                    onClick={() => setActiveImage(index)}
                    aria-label={`تصویر ${index + 1}`}
                  />
                ))}
              </div>
            </>
          ) : null}
        </div>

        <div className="product-modal__body">
          <h2 id="product-modal-title" className="product-modal__title">
            {product.name}
          </h2>
          {product.nameEn ? (
            <p className="product-modal__title-en" lang="en" dir="ltr">
              {product.nameEn}
            </p>
          ) : null}
          <p className="product-modal__price">
            {product.price != null ? (
              <>
                <span className="product-modal__price-value">
                  {formatPrice(product.price)}
                </span>
                <span className="product-modal__price-unit">تومان</span>
              </>
            ) : (
              <span className="product-modal__price-value">—</span>
            )}
          </p>
          <p className="product-modal__desc">{product.description}</p>
        </div>
      </div>
    </div>
  );
}
