import { UIEvent, useEffect, useRef, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import {
  fetchProduct,
  formatPrice,
  ORIGIN_LABELS,
  ProductDetail as ProductDetailType,
} from '../api'
import EmptyState from '../components/EmptyState'
import { IconExternal, IconLeaf } from '../components/Icons'
import OriginBadge from '../components/OriginBadge'
import ProductCard from '../components/ProductCard'
import Skeleton from '../components/Skeleton'
import StoreLogo from '../components/StoreLogo'

const DESCRIPTION_CLAMP = 280

export default function ProductDetail() {
  const { uid } = useParams<{ uid: string }>()
  const [product, setProduct] = useState<ProductDetailType | null>(null)
  const [error, setError] = useState(false)
  const [activeImage, setActiveImage] = useState(0)
  const [descExpanded, setDescExpanded] = useState(false)
  const trackRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!uid) return
    const controller = new AbortController()
    setProduct(null)
    setError(false)
    setActiveImage(0)
    setDescExpanded(false)
    fetchProduct(uid, controller.signal)
      .then(setProduct)
      .catch((err: unknown) => {
        if (err instanceof DOMException && err.name === 'AbortError') return
        setError(true)
      })
    window.scrollTo({ top: 0 })
    return () => controller.abort()
  }, [uid])

  function onTrackScroll(e: UIEvent<HTMLDivElement>) {
    const el = e.currentTarget
    if (el.clientWidth === 0) return
    const idx = Math.round(el.scrollLeft / el.clientWidth)
    if (idx !== activeImage) setActiveImage(idx)
  }

  function goToImage(i: number) {
    const el = trackRef.current
    if (!el) return
    el.scrollTo({ left: i * el.clientWidth, behavior: 'smooth' })
    setActiveImage(i)
  }

  if (error) {
    return (
      <div className="page">
        <EmptyState message="Produit introuvable.">
          <Link className="btn btn-secondary" to="/produits">
            Retour aux produits
          </Link>
        </EmptyState>
      </div>
    )
  }

  if (!product) {
    return (
      <div className="page">
        <div className="product-detail">
          <div className="product-detail-gallery">
            <Skeleton height="auto" radius="8px" className="skeleton-square" />
          </div>
          <div className="product-detail-info">
            <Skeleton height="2.2rem" width="80%" />
            <Skeleton height="1.6rem" width="30%" />
            <Skeleton height="1rem" width="100%" />
            <Skeleton height="1rem" width="90%" />
            <Skeleton height="3rem" width="60%" radius="8px" />
          </div>
        </div>
      </div>
    )
  }

  const images = product.images
  const hasDiscount =
    product.compare_at_price !== null &&
    product.price !== null &&
    product.compare_at_price > product.price
  const originLabel = ORIGIN_LABELS[product.origin_class] ?? ''
  const description = product.description ?? ''
  const descIsLong = description.length > DESCRIPTION_CLAMP

  return (
    <div className="page page-product-detail">
      <nav className="breadcrumb" aria-label="Fil d'Ariane">
        <Link to="/produits">Produits</Link>
        {product.category && (
          <>
            <span aria-hidden="true">/</span>
            <Link to={`/produits?category=${encodeURIComponent(product.category)}`}>
              {product.category}
            </Link>
          </>
        )}
      </nav>

      <div className="product-detail">
        <div className="product-detail-gallery">
          {images.length > 0 ? (
            <>
              <div
                className="pd-track"
                ref={trackRef}
                onScroll={onTrackScroll}
                aria-label={`Images du produit (${images.length})`}
              >
                {images.map((img, i) => (
                  <div className="pd-slide" key={`${img}-${i}`}>
                    <GalleryImage
                      src={img}
                      alt={i === 0 ? product.title : ''}
                      eager={i === 0}
                    />
                  </div>
                ))}
              </div>
              {images.length > 1 && (
                <>
                  <div className="pd-dots" aria-hidden="true">
                    {images.map((_, i) => (
                      <span
                        key={i}
                        className={i === activeImage ? 'pd-dot pd-dot-active' : 'pd-dot'}
                      />
                    ))}
                  </div>
                  <div className="product-detail-thumbs">
                    {images.map((img, i) => (
                      <button
                        key={`${img}-${i}`}
                        type="button"
                        className={i === activeImage ? 'thumb thumb-active' : 'thumb'}
                        onClick={() => goToImage(i)}
                        aria-label={`Image ${i + 1}`}
                      >
                        <img src={img} alt="" loading="lazy" />
                      </button>
                    ))}
                  </div>
                </>
              )}
            </>
          ) : (
            <div className="pd-track">
              <div className="pd-slide">
                <div className="image-placeholder" aria-hidden="true">
                  <IconLeaf size={44} />
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="product-detail-info">
          <div className="product-detail-badges">
            <OriginBadge origin={product.origin_class} withLabel />
            {!product.available && (
              <span className="unavailable-badge">Non disponible</span>
            )}
          </div>
          <h1 className="product-detail-title">{product.title}</h1>

          <div className="product-detail-price">
            {product.price !== null ? (
              <span className="price-chip price-chip-lg">
                {formatPrice(product.price)}
                {product.price_max !== null &&
                  product.price_max > product.price &&
                  ` – ${formatPrice(product.price_max)}`}
              </span>
            ) : (
              <span className="price-chip price-chip-muted">
                Prix affiché en boutique
              </span>
            )}
            {hasDiscount && (
              <s className="price-compare">
                {formatPrice(product.compare_at_price)}
              </s>
            )}
          </div>

          {description && (
            <div className="product-detail-description-wrap">
              <p
                className={
                  descIsLong && !descExpanded
                    ? 'product-detail-description product-detail-description-clamped'
                    : 'product-detail-description'
                }
              >
                {description}
              </p>
              {descIsLong && (
                <button
                  type="button"
                  className="desc-toggle"
                  onClick={() => setDescExpanded((v) => !v)}
                  aria-expanded={descExpanded}
                >
                  {descExpanded ? 'Réduire' : 'Lire la suite'}
                </button>
              )}
            </div>
          )}

          <dl className="product-detail-meta">
            {product.vendor && (
              <div>
                <dt>Marque</dt>
                <dd>{product.vendor}</dd>
              </div>
            )}
            {product.category && (
              <div>
                <dt>Catégorie</dt>
                <dd>{product.category}</dd>
              </div>
            )}
            {product.product_type && (
              <div>
                <dt>Type</dt>
                <dd>{product.product_type}</dd>
              </div>
            )}
            {originLabel && (
              <div>
                <dt>Origine</dt>
                <dd>{originLabel}</dd>
              </div>
            )}
          </dl>

          {product.tags.length > 0 && (
            <div className="tag-list">
              {product.tags.map((t) => (
                <span className="tag" key={t}>
                  {t}
                </span>
              ))}
            </div>
          )}

          <a
            className="btn btn-primary btn-cta"
            href={product.url}
            target="_blank"
            rel="noopener noreferrer"
          >
            Voir chez {product.store_name} <IconExternal size={16} />
          </a>

          <div className="card store-info-card">
            <span className="filter-label">Boutique</span>
            <div className="store-info-row">
              <StoreLogo
                storeId={product.store_id}
                name={product.store_name}
                size="sm"
              />
              <div className="store-info-text">
                <Link
                  to={`/boutiques/${encodeURIComponent(product.store_id)}`}
                  className="store-info-name"
                >
                  {product.store_name}
                </Link>
                <p className="store-info-location">
                  {[product.store_city, product.store_region]
                    .filter(Boolean)
                    .join(', ') || 'Québec'}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {product.related.length > 0 && (
        <section className="rail">
          <header className="section-header">
            <h2>Produits similaires</h2>
          </header>
          <div className="rail-track">
            {product.related.map((p) => (
              <div className="rail-item" key={p.uid}>
                <ProductCard product={p} />
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Mobile sticky CTA (safe-area aware) */}
      <div className="pd-cta-bar">
        <div className="pd-cta-price">
          {product.price !== null ? (
            <span className="price-chip">{formatPrice(product.price)}</span>
          ) : (
            <span className="price-chip price-chip-muted">Prix en boutique</span>
          )}
        </div>
        <a
          className="btn btn-primary pd-cta-btn"
          href={product.url}
          target="_blank"
          rel="noopener noreferrer"
        >
          Voir chez {product.store_name} <IconExternal size={15} />
        </a>
      </div>
    </div>
  )
}

function GalleryImage({
  src,
  alt,
  eager,
}: {
  src: string
  alt: string
  eager?: boolean
}) {
  const [failed, setFailed] = useState(false)
  if (failed) {
    return (
      <div className="image-placeholder" aria-hidden="true">
        <IconLeaf size={44} />
      </div>
    )
  }
  return (
    <img
      src={src}
      alt={alt}
      loading={eager ? 'eager' : 'lazy'}
      onError={() => setFailed(true)}
    />
  )
}
