import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Megaphone, Gift, Tag, Crown } from 'lucide-react'
import { getOngoingEvents, joinEvent, getLoyaltyMe } from '../api/client'
import { useShop } from '../store/shop'
import { useNavigate } from 'react-router-dom'
import StatusBadge from '../components/StatusBadge'

const TYPE_ICON: Record<string, any> = { DISCOUNT: Tag, POINT_BONUS: Crown, GIFT: Gift, TIER_ONLY: Crown, SEASON: Megaphone }

export default function Events() {
  const { custToken } = useShop()
  const nav = useNavigate()
  const [msg, setMsg] = useState('')
  const { data: loyalty } = useQuery({ queryKey: ['loyalty-me'], queryFn: getLoyaltyMe, enabled: !!custToken })
  const tier = loyalty?.tier || ''
  const { data: events } = useQuery({ queryKey: ['ongoing-events', tier], queryFn: () => getOngoingEvents(tier) })

  const join = async (id: number) => {
    if (!custToken) { nav('/account'); return }
    setMsg('')
    try {
      const r = await joinEvent(id)
      setMsg(r?.coupon ? `참여 완료! 쿠폰 발급: ${r.coupon.name} (${r.coupon.code})` : '이벤트에 참여했습니다.')
    } catch (e: any) {
      setMsg(e?.response?.data?.message || '참여 자격이 없거나 이미 참여했습니다.')
    }
  }

  return (
    <div className="max-w-5xl mx-auto px-4 py-8">
      <div className="flex items-center gap-2 mb-2"><Megaphone className="text-bloom" size={22} /><h1 className="font-serif text-2xl font-bold text-blush-900">이벤트 / 캠페인</h1></div>
      {tier && <p className="text-sm text-gray-500 mb-2">현재 등급 <span className="font-semibold text-bloom2">{loyalty?.tierName || tier}</span> · 등급 전용 이벤트가 함께 표시됩니다.</p>}
      {msg && <div className="bg-petal text-bloom2 text-sm rounded-xl px-4 py-2 mb-4">{msg}</div>}

      <div className="grid md:grid-cols-2 gap-4 mt-4">
        {(events || []).map((ev: any) => {
          const Icon = TYPE_ICON[ev.eventType] || Megaphone
          const banner = (ev.banners || [])[0]
          return (
            <div key={ev.id} className="bg-white rounded-2xl border border-blush-100/60 overflow-hidden">
              <div className="bg-gradient-to-r from-bloom2 to-bloom text-white p-5">
                {banner ? (<>
                  <div className="font-serif text-lg font-bold">{banner.headline || ev.title}</div>
                  <p className="text-white/85 text-sm mt-1">{banner.subtext || ev.description}</p>
                </>) : (<>
                  <div className="font-serif text-lg font-bold">{ev.title}</div>
                  <p className="text-white/85 text-sm mt-1">{ev.description}</p>
                </>)}
              </div>
              <div className="p-4 flex items-center justify-between">
                <div className="flex items-center gap-2 text-sm text-gray-600">
                  <Icon size={16} className="text-bloom" />
                  <span>{ev.eventType}</span>
                  {ev.bonusPointRate > 0 && <span className="text-xs text-leaf">+{ev.bonusPointRate}% 포인트</span>}
                  {ev.targetTiers && <span className="text-xs bg-petal text-bloom2 px-2 py-0.5 rounded-full">{ev.targetTiers} 전용</span>}
                </div>
                <div className="flex items-center gap-2">
                  <StatusBadge status={ev.status} />
                  <button onClick={() => join(ev.id)} className="bg-bloom text-white text-sm font-semibold px-4 py-2 rounded-full hover:bg-bloom2">참여</button>
                </div>
              </div>
              <div className="px-4 pb-3 text-[11px] text-gray-400">{ev.startDate} ~ {ev.endDate}</div>
            </div>
          )
        })}
        {!(events || []).length && <div className="col-span-2 text-center text-gray-400 py-16">진행 중인 이벤트가 없습니다.</div>}
      </div>
    </div>
  )
}
