import { useQuery } from '@tanstack/react-query'
import { Crown, Coins, Gift, User, LogOut, Package, Heart, Repeat } from 'lucide-react'
import { Link, useNavigate } from 'react-router-dom'
import { getMember, getLoyaltyMe, getPointHistory } from '../api/client'
import { useShop, money } from '../store/shop'

const TIER_COLOR: Record<string, string> = {
  BASIC: 'from-slate-400 to-slate-500', SILVER: 'from-slate-300 to-slate-400',
  GOLD: 'from-amber-400 to-amber-500', VIP: 'from-violet-500 to-fuchsia-500',
}

export default function Mypage() {
  const { custToken, setCustToken } = useShop()
  const nav = useNavigate()
  const { data: member } = useQuery({ queryKey: ['member'], queryFn: getMember, enabled: !!custToken })
  const { data: loy } = useQuery({ queryKey: ['loyalty-me'], queryFn: getLoyaltyMe, enabled: !!custToken })
  const { data: history } = useQuery({ queryKey: ['point-history'], queryFn: () => getPointHistory(20), enabled: !!custToken })

  if (!custToken) { nav('/account'); return null }
  const tier = loy?.tier || 'BASIC'
  const next = loy?.nextTier

  const logout = () => { setCustToken(null); nav('/home') }

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2"><User className="text-bloom" size={22} /><h1 className="font-serif text-2xl font-bold text-blush-900">My Account</h1></div>
        <button onClick={logout} className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-bloom"><LogOut size={16} /> Log Out</button>
      </div>

      {/* 등급 카드 */}
      <div className={`rounded-2xl bg-gradient-to-r ${TIER_COLOR[tier] || TIER_COLOR.BASIC} text-white p-6 mb-5`}>
        <div className="flex items-center justify-between">
          <div>
            <div className="text-xs uppercase tracking-widest text-white/70">Membership Tier</div>
            <div className="font-serif text-2xl font-bold flex items-center gap-2"><Crown size={24} /> {loy?.tierName || tier}</div>
            <div className="text-sm text-white/85 mt-1">Spent in last 12 months {money(loy?.spend12m)} · {loy?.orderCount12m || 0} orders</div>
          </div>
          <div className="text-right">
            <div className="text-xs text-white/70">Points Balance</div>
            <div className="text-3xl font-bold">{(loy?.pointBalance || 0).toLocaleString()}<span className="text-base">P</span></div>
          </div>
        </div>
        {next && !next.isTop && (
          <div className="mt-4 text-xs text-white/85 bg-white/15 rounded-lg px-3 py-2">
            Spend {money(next.spendNeeded)} more or place {next.ordersNeeded} more orders to reach <b>{next.nextTierName}</b>.
          </div>
        )}
      </div>

      {/* 등급 혜택 */}
      {loy?.benefit && (
        <div className="bg-white rounded-2xl border border-blush-100/60 p-5 mb-5">
          <div className="text-sm font-semibold mb-3 flex items-center gap-2"><Gift size={16} className="text-bloom" /> My Tier Benefits</div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
            <Benefit label="Discount" value={`${loy.benefit.discountRate}%`} />
            <Benefit label="Earn Rate" value={`${loy.benefit.pointEarnRate}%`} />
            <Benefit label="Free Shipping" value={loy.benefit.freeShipThreshold === 0 ? 'Always' : loy.benefit.freeShipThreshold ? money(loy.benefit.freeShipThreshold) + '+' : 'None'} />
            <Benefit label="Priority Slot" value={loy.benefit.prioritySlot ? 'Included' : '–'} />
          </div>
        </div>
      )}

      {/* 빠른 메뉴 */}
      <div className="grid grid-cols-3 gap-3 mb-6">
        <Quick to="/orders" icon={Package} label="Order History" />
        <Quick to="/wishlist" icon={Heart} label="Wishlist" />
        <Quick to="/subscription" icon={Repeat} label="Manage Subscription" />
      </div>

      {/* 포인트 이력 */}
      <div className="bg-white rounded-2xl border border-blush-100/60 p-5">
        <div className="text-sm font-semibold mb-3 flex items-center gap-2"><Coins size={16} className="text-bloom" /> Points Earned / Used History</div>
        <div className="divide-y divide-blush-100/60">
          {(history || []).map((h: any) => (
            <div key={h.id} className="flex items-center justify-between py-2 text-sm">
              <div>
                <span className="text-gray-700">{h.reason || h.entryType}</span>
                {h.orderNo && <span className="text-xs text-gray-400 ml-2">{h.orderNo}</span>}
                <div className="text-[11px] text-gray-400">{(h.createdAt || '').slice(0, 10)}</div>
              </div>
              <span className={h.points >= 0 ? 'text-leaf font-semibold' : 'text-blush-500 font-semibold'}>{h.points >= 0 ? '+' : ''}{h.points}P</span>
            </div>
          ))}
          {!(history || []).length && <div className="text-gray-400 text-sm py-6 text-center">No points history yet.</div>}
        </div>
      </div>

      {member?.username && <div className="text-center text-xs text-gray-400 mt-6">{member.displayName || member.username}</div>}
    </div>
  )
}

function Benefit({ label, value }: { label: string; value: string }) {
  return <div className="bg-petal rounded-xl p-3 text-center"><div className="text-[11px] text-gray-500">{label}</div><div className="font-bold text-bloom2">{value}</div></div>
}
function Quick({ to, icon: Icon, label }: { to: string; icon: any; label: string }) {
  return <Link to={to} className="bg-white rounded-2xl border border-blush-100/60 p-4 flex flex-col items-center gap-1.5 hover:border-bloom"><Icon size={22} className="text-bloom" /><span className="text-sm">{label}</span></Link>
}
