import { useEffect, useMemo, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { ChevronLeft, ChevronRight, Minus, Plus, Star } from 'lucide-react'
import PageHeader from '../components/PageHeader'
import ProductCard from '../components/ProductCard'
import ProductOptionsModal from '../components/ProductOptionsModal'
import { getProduct, listProducts } from '../lib/api'
import { addToCart } from '../lib/cart'
import type { Product, ProductOptionValue } from '../lib/types'
import { formatProductPrice, productImageSrc } from '../lib/types'
import handbagIcon from '../assets/images/Handbag.svg'
import cakeIcon from '../assets/images/Cake.svg'
import defaultPhoto from '../assets/images/DefaultPhoto.png'
import './ProductDetailPage.css'

function stripHtml(value: string) {
  return value
    .replace(/<[^>]*>/g, ' ')
    .replace(/&nbsp;/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()
}

export default function ProductDetailPage() {
  const { slugOrId = '', id = '' } = useParams()
  const productId = id || slugOrId
  const [product, setProduct] = useState<Product | null>(null)
  const [related, setRelated] = useState<Product[]>([])
  const [activeImage, setActiveImage] = useState<string>('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [quantity, setQuantity] = useState(1)
  const [optionsOpen, setOptionsOpen] = useState(false)

  useEffect(() => {
    document.title = 'شیرینی بلوط - صفحه جزئیات محصول'
  }, [])

  useEffect(() => {
    if (!productId) return
    let cancelled = false
    setLoading(true)
    setError(null)
    setProduct(null)
    setRelated([])

    getProduct(productId)
      .then((item) => {
        if (cancelled) return
        setProduct(item)
        const galleryUrls = [
          item.mainImageUrl,
          ...(item.gallery ?? []).map((g) => g.url),
        ].filter(Boolean) as string[]
        setActiveImage(galleryUrls[0] || defaultPhoto)
        setLoading(false)

        listProducts({
          categoryId: item.categoryId,
          page: 1,
          pageSize: 8,
        })
          .then((relatedResult) => {
            if (cancelled) return
            setRelated(relatedResult.items.filter((p) => p.id !== item.id).slice(0, 4))
          })
          .catch(() => {
            if (!cancelled) setRelated([])
          })
      })
      .catch((err: Error) => {
        if (cancelled) return
        setError(err.message || 'محصول یافت نشد')
        setLoading(false)
      })

    return () => {
      cancelled = true
    }
  }, [productId])

  const thumbs = useMemo(() => {
    if (!product) return []
    const urls = [
      product.mainImageUrl,
      ...(product.gallery ?? []).map((g) => g.url),
    ].filter(Boolean) as string[]
    if (urls.length === 0) return [defaultPhoto]
    const unique = [...new Set(urls)]
    if (unique.length === 1) return [unique[0], unique[0]]
    return unique.slice(0, 6)
  }, [product])

  const price = product ? formatProductPrice(product) : null
  const abstractText = product?.intro ? stripHtml(product.intro) : ''
  const descriptionHtml = product?.description?.trim() || ''
  const isWeight = product?.sellUnit === 'kilo'
  const qtyStep = isWeight ? 0.1 : 1
  const qtyMin = isWeight ? 0.1 : 1

  function bumpQuantity(delta: number) {
    setQuantity((current) => {
      const next = Number((current + delta).toFixed(3))
      return next < qtyMin ? qtyMin : next
    })
  }

  function commitAdd(options: ProductOptionValue[] = []) {
    if (!product) return
    addToCart({ product, quantity, options })
    setOptionsOpen(false)
  }

  function handleAddClick() {
    if (!product) return
    if ((product.options?.length ?? 0) > 0) {
      setOptionsOpen(true)
      return
    }
    commitAdd()
  }

  useEffect(() => {
    setQuantity(product?.sellUnit === 'kilo' ? 0.5 : 1)
    setOptionsOpen(false)
  }, [product?.id, product?.sellUnit])

  return (
    <div className="product-detail">
      <div className="max-container product-detail__top">
        <Link to="/products" className="product-detail__back">
          <ChevronRight size={16} strokeWidth={2} />
          بازگشت به محصولات
        </Link>
      </div>

      <PageHeader
        icon={handbagIcon}
        placeholder="Product Details"
        secondary="جزئیات"
        primary="محصــــول ما"
        crumbs={[
          { label: 'صفحه اصلی', to: '/' },
          { label: 'محصولات', to: '/products' },
          { label: 'جزئیات محصول' },
        ]}
      />

      <div className="max-container">
        {loading && (
          <div className="product-detail__state">
            <div className="product-detail__spinner" />
            <p>در حال بارگذاری...</p>
          </div>
        )}

        {!loading && error && (
          <div className="product-detail__state product-detail__state--error">
            <p>{error}</p>
            <Link to="/products" className="btn-primary">
              بازگشت به محصولات
            </Link>
          </div>
        )}

        {!loading && product && price && (
          <>
            <div className="product-detail__grid">
              <div className="product-images">
                <div className="product-images__main">
                  <img src={activeImage || productImageSrc(product, defaultPhoto)} alt={product.nameFa} />
                </div>
                <div className="product-images__thumbs">
                  {thumbs.map((url, index) => (
                    <button
                      key={`${url}-${index}`}
                      type="button"
                      className={activeImage === url ? 'is-active' : undefined}
                      onClick={() => setActiveImage(url)}
                    >
                      <img src={url} alt="" />
                    </button>
                  ))}
                </div>
              </div>

              <div className="product-detail__info">
                <div className="product--name">{product.nameFa}</div>

                <div className="product-detail__meta">
                  <div className="product-detail__rating" aria-label="امتیاز ۵ از ۵">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Star key={i} size={18} fill="currentColor" strokeWidth={0} />
                    ))}
                  </div>
                  <div className="product--price">
                    {price.amount}{' '}
                    <span className="product--currency-unit">تومان</span>
                    <span className="product--currency-unit"> / {price.unitLabel}</span>
                  </div>
                </div>

                {abstractText && (
                  <div className="product-detail__block">
                    <div className="caption__title">توضیحات :</div>
                    <div className="caption__text">{abstractText}</div>
                  </div>
                )}

                <div className="product-detail__block">
                  <div className="caption__title">
                    {' '}
                    دسته بندی :{' '}
                    <span className="caption__text">{product.category?.nameFa ?? '—'}</span>
                  </div>
                </div>

                <div className="product-detail__cart-wrap">
                  <div className="qty-stepper" dir="ltr">
                    <button
                      type="button"
                      className="qty-stepper__btn"
                      aria-label="کم کردن"
                      onClick={() => bumpQuantity(-qtyStep)}
                    >
                      <Minus size={16} />
                    </button>
                    <input
                      className="qty-stepper__input"
                      type="number"
                      min={qtyMin}
                      step={qtyStep}
                      value={quantity}
                      onChange={(e) => {
                        const next = Number(e.target.value)
                        if (!Number.isFinite(next)) return
                        setQuantity(next < qtyMin ? qtyMin : next)
                      }}
                      aria-label="تعداد"
                    />
                    <button
                      type="button"
                      className="qty-stepper__btn"
                      aria-label="افزایش"
                      onClick={() => bumpQuantity(qtyStep)}
                    >
                      <Plus size={16} />
                    </button>
                  </div>
                  <button
                    type="button"
                    className="btn-primary product-detail__cart"
                    onClick={handleAddClick}
                  >
                    افزودن به سبد خرید
                    <ChevronLeft size={14} />
                  </button>
                </div>
              </div>
            </div>

            {product && (
              <ProductOptionsModal
                open={optionsOpen}
                product={product}
                quantity={quantity}
                onClose={() => setOptionsOpen(false)}
                onConfirm={commitAdd}
              />
            )}

            {descriptionHtml && (
              <section className="product-detail__description">
                <div className="caption__title">توضیحات محصول :</div>
                <div
                  className="product-detail__description-body"
                  dangerouslySetInnerHTML={{ __html: descriptionHtml }}
                />
              </section>
            )}

            <div className="product-detail__related">
              <div className="product-detail__related-title">
                <img src={cakeIcon} alt="" className="product-detail__related-icon" />
                <div className="text-start texts--separated size-md">
                  <div className="header-title">
                    <p className="header-title__placeholder">Related Products</p>
                    <div className="header-title--top">
                      <p className="header-title__secondary">محصولات</p>
                      <p className="header-title__primary">مشابــــــــــــــــــــه</p>
                    </div>
                  </div>
                </div>
              </div>

              {related.length > 0 ? (
                <div className="product-detail__related-grid">
                  {related.map((item) => (
                    <ProductCard key={item.id} product={item} />
                  ))}
                </div>
              ) : (
                <p className="product-detail__related-empty">محصول مشابهی یافت نشد.</p>
              )}

              <div className="product-detail__related-actions">
                <Link to="/products" className="btn-primary">
                  مشاهده همه محصولات
                  <ChevronLeft size={14} />
                </Link>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  )
}
