import { useState } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { motion, useReducedMotion } from 'framer-motion'
import { Flower2, Star, Heart, Sparkles, ShoppingCart, Truck, ShieldCheck } from 'lucide-react'
import { getProduct, getReviews, getReviewStats, aiReviewSummary, addToCart, addWishlist } from '../api/client'
import { money, useShop } from '../store/shop'
import { Reveal, Pressable } from './components/motion'
import { ShareButtons } from './components/social'
import { Product, ProductOption } from '../types'

export default function ProductDetail() {
  const { id } = useParams()
  const pid = Number(id)
  const nav = useNavigate()
  const reduce = useReducedMotion()
  const { custToken, setCartCount } = useShop()
  const [sizeCode, setSizeCode] = useState('')
  const [vaseId, setVaseId] = useState<number | null>(null)
  const [wrapId, setWrapId] = useState<number | null>(null)
  const [cardMessage, setCardMessage] = useState('')
  const [qty, setQty] = useState(1)
  const [msg, setMsg] = useState('')
  const [heart, setHeart] = useState(false)
  const [activeImg, setActiveImg] = useState<string | null>(null)

  const { data: p } = useQuery<Product>({ queryKey: ['product', pid], queryFn: () => getProduct(pid) })
  const { data: reviews } = useQuery({ queryKey: ['reviews', pid], queryFn: () => getReviews(pid) })
  const { data: stats } = useQuery({ queryKey: ['rstats', pid], queryFn: () => getReviewStats(pid) })
  const { data: aiSum } = useQuery({ queryKey: ['aisum', pid], queryFn: () => aiReviewSummary(pid) })

  if (!p) return <div className="max-w-6xl mx-auto px-4 py-24 text-center text-blush-300">Loading…</div>

  const sizes = p.sizes || []
  const activeSize = sizes.find(s => s.sizeCode === sizeCode) || sizes[0]
  const opts = p.options || []
  const vases = opts.filter(o => o.optionType === 'VASE')
  const wraps = opts.filter(o => o.optionType === 'WRAP')
  const findOpt = (oid: number | null): ProductOption | undefined => opts.find(o => o.id === oid)
  const basePrice = activeSize ? activeSize.price : (p.salePrice && p.salePrice > 0 ? p.salePrice : p.price)
  const extra = (findOpt(vaseId)?.extraPrice || 0) + (findOpt(wrapId)?.extraPrice || 0)
  const total = (basePrice + extra) * qty
  const mainImg = activeImg || p.thumbnail

  const add = async () => {
    if (!custToken) { nav('/account'); return }
    try {
      await addToCart({ productId: p.id, optionId: vaseId || wrapId || null, sizeCode: activeSize?.sizeCode || '', cardMessage, quantity: qty })
      setCartCount((c: number) => c + qty)
      setMsg('Added to your cart.')
    } catch { setMsg('Could not add to cart.') }
  }
  const buy = async () => { await add(); nav('/cart') }
  const wish = async () => {
    if (!custToken) { nav('/account'); return }
    setHeart(true); setTimeout(() => setHeart(false), 700)
    await addWishlist(p.id).catch(() => {}); setMsg('Saved to your wishlist.')
  }

  return (
    <div className="max-w-6xl mx-auto px-4 py-10">
      <div className="grid md:grid-cols-2 gap-10">
        {/* 갤러리 */}
        <Reveal>
          <div className="relative aspect-[4/5] rounded-4xl overflow-hidden bg-gradient-to-br from-blush-50 to-ivory flex items-center justify-center shadow-soft">
            {mainImg ? (
              <motion.img key={mainImg} src={mainImg} alt={p.name}
                initial={reduce ? false : { opacity: 0, scale: 1.04 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.6 }}
                className="w-full h-full object-cover" />
            ) : <Flower2 className="text-blush-200" size={96} />}
          </div>
          {!!(p.images || []).length && (
            <div className="flex gap-2 mt-3">
              <button onClick={() => setActiveImg(null)} className={`w-16 h-16 rounded-2xl overflow-hidden border-2 ${!activeImg ? 'border-blush-400' : 'border-blush-100'}`}>
                {p.thumbnail ? <img src={p.thumbnail} className="w-full h-full object-cover" /> : <Flower2 className="text-blush-200 m-auto" size={20} />}
              </button>
              {p.images.map((im, i) => (
                <button key={i} onClick={() => setActiveImg(im)} className={`w-16 h-16 rounded-2xl overflow-hidden border-2 ${activeImg === im ? 'border-blush-400' : 'border-blush-100'}`}>
                  <img src={im} className="w-full h-full object-cover" />
                </button>
              ))}
            </div>
          )}
        </Reveal>

        {/* 정보 */}
        <Reveal delay={0.1}>
          {p.brand && <div className="text-[11px] uppercase tracking-[0.2em] text-sage-600 mb-1">{p.brand}</div>}
          <h1 className="font-serif text-3xl font-bold text-blush-900 mb-2 leading-tight">{p.name}</h1>
          <div className="flex items-center gap-2 text-sm text-gold mb-4">
            <Star size={15} fill="currentColor" /> {p.ratingAvg?.toFixed(1) || '–'}
            <span className="text-[#a08a90]">({p.reviewCount || 0} reviews)</span>
            {p.occasion && <span className="text-xs bg-blush-50 text-blush-700 px-2.5 py-0.5 rounded-full ml-1">{p.occasion}</span>}
          </div>
          <p className="text-[#6b5258] text-[15px] mb-6 leading-relaxed">{p.description}</p>

          {/* 3사이즈 토글 (Bouqs) */}
          {!!sizes.length && (
            <div className="mb-6">
              <div className="text-sm font-medium text-blush-900 mb-2">Choose your size</div>
              <div className="grid grid-cols-3 gap-2.5">
                {sizes.map(s => (
                  <Pressable key={s.sizeCode} onClick={() => setSizeCode(s.sizeCode)}
                    className={`rounded-2xl border p-3 text-center transition-colors ${activeSize?.sizeCode === s.sizeCode ? 'border-blush-400 bg-blush-50' : 'border-blush-100 hover:border-blush-300'}`}>
                    <div className="font-semibold text-sm text-blush-900">{s.label}</div>
                    <div className="text-xs text-[#8a7077]">{s.stemCount} stems</div>
                    <div className="text-blush-600 font-bold text-sm mt-1">{money(s.price)}</div>
                  </Pressable>
                ))}
              </div>
            </div>
          )}

          {/* 옵션: 화병 / 포장 */}
          {!!vases.length && (
            <div className="mb-4">
              <div className="text-sm font-medium text-blush-900 mb-2">Add a vase</div>
              <div className="flex flex-wrap gap-2">
                <Chip active={vaseId === null} onClick={() => setVaseId(null)}>No vase</Chip>
                {vases.map(o => <Chip key={o.id} active={vaseId === o.id} onClick={() => setVaseId(o.id)}>{o.optionValue} +{money(o.extraPrice)}</Chip>)}
              </div>
            </div>
          )}
          {!!wraps.length && (
            <div className="mb-4">
              <div className="text-sm font-medium text-blush-900 mb-2">Wrapping</div>
              <div className="flex flex-wrap gap-2">
                <Chip active={wrapId === null} onClick={() => setWrapId(null)}>Standard</Chip>
                {wraps.map(o => <Chip key={o.id} active={wrapId === o.id} onClick={() => setWrapId(o.id)}>{o.optionValue} +{money(o.extraPrice)}</Chip>)}
              </div>
            </div>
          )}
          <div className="mb-5">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium text-blush-900">Card message</span>
              <Link to="/cs" className="text-xs text-blush-500 flex items-center gap-1"><Sparkles size={12} /> AI message helper</Link>
            </div>
            <textarea value={cardMessage} onChange={e => setCardMessage(e.target.value)} rows={2} maxLength={200}
              placeholder="Write a heartfelt note for the recipient…"
              className="w-full px-3.5 py-2.5 rounded-2xl border border-blush-100 text-sm outline-none focus:border-blush-400" />
          </div>

          <div className="flex items-center gap-3 mb-5">
            <div className="flex items-center border border-blush-100 rounded-full">
              <button onClick={() => setQty(q => Math.max(1, q - 1))} className="px-3.5 py-1.5 text-blush-600">−</button>
              <span className="px-2 text-sm w-8 text-center">{qty}</span>
              <button onClick={() => setQty(q => q + 1)} className="px-3.5 py-1.5 text-blush-600">+</button>
            </div>
            <div className="font-serif text-2xl font-bold text-blush-900">{money(total)}</div>
          </div>

          {msg && <div className="text-sm text-sage-700 mb-3">{msg}</div>}
          <div className="flex gap-3">
            <Pressable onClick={add} className="flex-1 flex items-center justify-center gap-2 border border-blush-400 text-blush-600 font-semibold py-3.5 rounded-full hover:bg-blush-50"><ShoppingCart size={18} /> Add to Cart</Pressable>
            <Pressable onClick={buy} className="flex-1 bg-blush-500 text-white font-semibold py-3.5 rounded-full hover:bg-blush-600 shadow-petal">Buy Now</Pressable>
            <button onClick={wish} className={`px-4 border border-blush-100 rounded-full text-blush-500 hover:bg-blush-50 ${heart ? 'animate-heartbeat' : ''}`}><Heart size={18} fill={heart ? 'currentColor' : 'none'} /></button>
          </div>

          <div className="flex items-center gap-5 mt-5 text-xs text-sage-700">
            <span className="flex items-center gap-1.5"><Truck size={14} /> Same-day local delivery</span>
            <span className="flex items-center gap-1.5"><ShieldCheck size={14} /> 100% satisfaction</span>
          </div>

          {/* SNS 공유 (Instagram / Facebook / Pinterest) */}
          <div className="mt-4 pt-4 border-t border-blush-100/60">
            <ShareButtons
              url={typeof window !== 'undefined' ? window.location.href : ''}
              title={p.name}
              image={p.thumbnail || ''}
            />
          </div>
        </Reveal>
      </div>

      {/* 리뷰 + AI 요약 */}
      <div className="mt-16">
        <div className="botanical-divider mb-8"><Flower2 size={16} /></div>
        <h2 className="font-serif text-2xl font-bold text-blush-900 mb-5">Reviews ({stats?.count ?? p.reviewCount ?? 0})</h2>
        {aiSum?.summary && (
          <Reveal className="bg-gradient-to-br from-blush-50 to-sage-50 border border-blush-100 rounded-3xl p-5 mb-6">
            <div className="flex items-center gap-2 text-blush-700 font-medium text-sm mb-1.5"><Sparkles size={15} /> AI Review Summary <span className="text-xs text-[#a08a90]">{aiSum.source}</span></div>
            <p className="text-sm text-[#5a474d] leading-relaxed">{aiSum.summary}</p>
          </Reveal>
        )}
        <div className="space-y-3">
          {(reviews || []).map((r: any) => (
            <div key={r.id} className="bg-white rounded-3xl border border-blush-100/70 p-5 shadow-soft">
              <div className="flex items-center justify-between">
                <span className="font-medium text-sm text-blush-900">{r.title || 'Review'}</span>
                <span className="flex items-center gap-0.5 text-gold text-sm"><Star size={13} fill="currentColor" />{r.rating}</span>
              </div>
              <p className="text-sm text-[#6b5258] mt-1.5 leading-relaxed">{r.content}</p>
            </div>
          ))}
          {!(reviews || []).length && <div className="text-blush-300 text-sm py-8 text-center">No reviews yet — be the first.</div>}
        </div>
        <Link to={`/review/${p.id}`} className="inline-flex items-center gap-1 mt-5 text-sm text-blush-500 font-semibold hover:text-blush-700">Write a review →</Link>
      </div>
    </div>
  )
}

function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
  return (
    <button onClick={onClick}
      className={`px-3.5 py-1.5 rounded-full text-sm border transition-colors ${active ? 'bg-blush-500 text-white border-blush-500' : 'border-blush-100 text-[#6b5258] hover:border-blush-300'}`}>
      {children}
    </button>
  )
}
