import { useEffect, useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { Truck, Store as StoreIcon, CalendarDays, Clock, Sparkles, MapPin, CheckCircle2, AlertTriangle } from 'lucide-react'
import {
  getCart, getStores, getAvailability, getHolidays, addressVerify, taxQuote,
  getLoyaltyMe, checkout, createPayment,
} from '../api/client'
import { money, useShop } from '../store/shop'
import { PaymentSection, PayMethod } from './components/payments'
import { BRAND } from './brand'

function nextDays(n: number) {
  const out: string[] = []
  const d = new Date()
  for (let i = 0; i < n; i++) { const x = new Date(d); x.setDate(d.getDate() + i); out.push(x.toISOString().slice(0, 10)) }
  return out
}

export default function Checkout() {
  const nav = useNavigate()
  const { custToken, storeId: ctxStoreId, zip: ctxZip, setCartCount } = useShop()
  const [fulfillment, setFulfillment] = useState<'DELIVERY' | 'PICKUP'>('DELIVERY')
  const [storeId, setStoreId] = useState<number>(ctxStoreId || 0)
  const [date, setDate] = useState('')
  const [slot, setSlot] = useState<{ id: number; label: string } | null>(null)
  const [receiverName, setReceiverName] = useState('')
  const [receiverPhone, setReceiverPhone] = useState('')
  const [address, setAddress] = useState('')
  const [deliveryZip, setDeliveryZip] = useState(ctxZip || '')
  const [cardMessage, setCardMessage] = useState('')
  const [memo, setMemo] = useState('')
  const [usePointsAmt, setUsePointsAmt] = useState(0)
  const [payMethod, setPayMethod] = useState<PayMethod>('CARD')
  const [card, setCard] = useState<{ last4: string; expiry: string; complete: boolean }>({ last4: '', expiry: '', complete: false })
  const [addrCheck, setAddrCheck] = useState<any>(null)
  const [tax, setTax] = useState<any>(null)
  const [placing, setPlacing] = useState(false)
  const [done, setDone] = useState<any>(null)
  const [err, setErr] = useState('')

  const { data: cart } = useQuery({ queryKey: ['cart'], queryFn: getCart, enabled: !!custToken })
  const { data: stores } = useQuery({ queryKey: ['stores'], queryFn: () => getStores(true) })
  const { data: loyalty } = useQuery({ queryKey: ['loyalty-me'], queryFn: getLoyaltyMe, enabled: !!custToken })
  const { data: holidays } = useQuery({ queryKey: ['holidays'], queryFn: getHolidays })
  const { data: avail } = useQuery({
    queryKey: ['avail', storeId, date],
    queryFn: () => getAvailability(storeId, date),
    enabled: !!storeId && !!date,
  })

  useEffect(() => { if (!storeId && stores?.length) setStoreId(stores[0].id) }, [stores])

  const items = cart || []
  const subtotal = items.reduce((s: number, i: any) => s + (i.price || (i.unitPrice || 0) * (i.quantity || 1)), 0)
  const surge = avail?.surgeMultiplier && avail.surgeMultiplier > 1 ? subtotal * (avail.surgeMultiplier - 1) : 0
  const discountRate = loyalty?.benefit?.discountRate || 0
  const tierDiscount = subtotal * (discountRate / 100)
  const taxAmount = tax?.taxAmount || 0
  const pointBalance = loyalty?.pointBalance || 0
  const maxUsablePoints = Math.min(pointBalance, Math.floor(subtotal))
  const grand = Math.max(0, subtotal + surge + taxAmount - tierDiscount - usePointsAmt)

  const holidaySet = useMemo(() => new Set((holidays || []).filter((h: any) => h.blocked).map((h: any) => h.holidayDate)), [holidays])

  const verifyAddr = async () => {
    if (!address || !deliveryZip) return
    const r = await addressVerify(address, deliveryZip).catch(() => null)
    setAddrCheck(r)
  }
  const quoteTax = async () => {
    const st = stores?.find((s: any) => s.id === storeId)?.state || ''
    const r = await taxQuote(subtotal, deliveryZip || '', st).catch(() => null)
    setTax(r)
  }
  useEffect(() => { if (subtotal > 0 && storeId) quoteTax() }, [subtotal, storeId, deliveryZip])

  const placeOrder = async () => {
    setErr('')
    if (!custToken) { nav('/account'); return }
    if (!items.length) { setErr('Your cart is empty.'); return }
    if (!date || !slot) { setErr('Please select a delivery/pickup date and time slot.'); return }
    if (fulfillment === 'DELIVERY' && (!address || !receiverName)) { setErr('Please enter the recipient and delivery address.'); return }
    if (payMethod === 'CARD' && !card.complete) { setErr('Please enter your card details.'); return }
    setPlacing(true)
    try {
      const order = await checkout({
        storeId, fulfillmentType: fulfillment, receiverName, receiverPhone,
        address: fulfillment === 'DELIVERY' ? address : '', deliveryZip,
        scheduledDate: date, slotId: slot.id, slotLabel: slot.label,
        cardMessage, memo, couponId: null,
        discountAmount: Math.round((tierDiscount + usePointsAmt) * 100) / 100,
        taxAmount, surgeAmount: Math.round(surge * 100) / 100,
      })
      // 결제 게이트웨이 경유 (mock/Stripe) — 카드 전체번호 미보관, 마지막 4자리만 참조용 전달
      await createPayment({
        orderId: order.id, amount: grand, method: payMethod, usePoints: usePointsAmt,
        cardLast4: payMethod === 'CARD' ? card.last4 : '',
      }).catch(() => {})
      setCartCount(0)
      setDone(order)
    } catch (e: any) {
      setErr(e?.response?.data?.message || 'Order failed. Please try again in a moment.')
    } finally { setPlacing(false) }
  }

  if (!custToken) { nav('/account'); return null }

  if (done) return (
    <div className="max-w-lg mx-auto px-4 py-20 text-center">
      <CheckCircle2 className="mx-auto text-leaf mb-4" size={56} />
      <h1 className="font-serif text-2xl font-bold mb-2">Your order has been placed</h1>
      <p className="text-gray-500 mb-1">Order Number <span className="font-semibold text-bloom2">{done.orderNo || `#${done.id}`}</span></p>
      <p className="text-sm text-gray-500 mb-6">{date} · {slot?.label} · {money(grand)}</p>
      <div className="flex gap-3 justify-center">
        <button onClick={() => nav('/orders')} className="bg-bloom text-white px-6 py-2.5 rounded-full font-semibold">Order History</button>
        <button onClick={() => nav('/home')} className="border border-blush-100 px-6 py-2.5 rounded-full text-bloom2">Continue Shopping</button>
      </div>
    </div>
  )

  return (
    <div className="max-w-5xl mx-auto px-4 py-8">
      <h1 className="font-serif text-2xl font-bold mb-6">Checkout</h1>
      <div className="grid md:grid-cols-3 gap-6">
        <div className="md:col-span-2 space-y-5">
          {/* 수령 방식 */}
          <section className="bg-white rounded-2xl border border-blush-100/60 p-5">
            <div className="text-sm font-semibold mb-3">Fulfillment Method</div>
            <div className="grid grid-cols-2 gap-3">
              <button onClick={() => setFulfillment('DELIVERY')} className={`flex items-center gap-2 justify-center py-3 rounded-xl border ${fulfillment === 'DELIVERY' ? 'border-bloom bg-petal text-bloom2' : 'border-blush-100'}`}><Truck size={18} /> Local Delivery</button>
              <button onClick={() => setFulfillment('PICKUP')} className={`flex items-center gap-2 justify-center py-3 rounded-xl border ${fulfillment === 'PICKUP' ? 'border-bloom bg-petal text-bloom2' : 'border-blush-100'}`}><StoreIcon size={18} /> Store Pickup</button>
            </div>
            <div className="mt-3">
              <label className="block text-xs text-gray-500 mb-1">Store</label>
              <select value={storeId} onChange={e => setStoreId(Number(e.target.value))} className="w-full px-3 py-2 rounded-xl border border-blush-100 text-sm bg-white">
                {(stores || []).map((s: any) => <option key={s.id} value={s.id}>{s.name} ({s.city}, {s.state})</option>)}
              </select>
            </div>
          </section>

          {/* 날짜 + 타임슬롯 (UrbanStems/Ode) */}
          <section className="bg-white rounded-2xl border border-blush-100/60 p-5">
            <div className="flex items-center gap-2 text-sm font-semibold mb-3"><CalendarDays size={16} className="text-bloom" /> Delivery / Pickup Date</div>
            <div className="flex gap-2 overflow-x-auto pb-2">
              {nextDays(14).map(d => {
                const blocked = holidaySet.has(d)
                const sel = date === d
                const dd = new Date(d)
                return (
                  <button key={d} disabled={blocked} onClick={() => { setDate(d); setSlot(null) }}
                    className={`shrink-0 w-16 py-2 rounded-xl border text-center text-xs ${blocked ? 'opacity-30 cursor-not-allowed border-blush-100' : sel ? 'border-bloom bg-bloom text-white' : 'border-blush-100 hover:border-bloom'}`}>
                    <div className="font-semibold">{dd.toLocaleDateString('en-US', { weekday: 'short' })}</div>
                    <div className="text-base">{dd.getDate()}</div>
                    {blocked && <div className="text-[9px]">Closed</div>}
                  </button>
                )
              })}
            </div>
            {date && avail && (
              <div className="mt-3">
                {avail.blocked && <div className="flex items-center gap-1.5 text-blush-500 text-xs mb-2"><AlertTriangle size={13} /> Delivery is unavailable on this date (peak season / closed).</div>}
                {avail.surgeMultiplier > 1 && <div className="text-xs text-amber-600 mb-2">⚡ Peak-season surge pricing ×{avail.surgeMultiplier} applied</div>}
                {avail.sameDayAvailable && <div className="text-xs text-leaf mb-2">Same-Day Delivery available (order by {avail.sameDayCutoff})</div>}
                <div className="flex items-center gap-2 text-sm font-medium mb-2"><Clock size={14} className="text-bloom" /> Delivery Time Slot</div>
                <div className="grid grid-cols-3 gap-2">
                  {(avail.slots || []).map((s: any) => {
                    const full = s.available === false || (s.capacity != null && s.booked >= s.capacity)
                    return (
                      <button key={s.id} disabled={full} onClick={() => setSlot({ id: s.id, label: s.slotLabel })}
                        className={`py-2 rounded-lg border text-xs ${full ? 'opacity-30 cursor-not-allowed' : slot?.id === s.id ? 'border-bloom bg-petal text-bloom2 font-semibold' : 'border-blush-100 hover:border-bloom'}`}>
                        {s.slotLabel}
                      </button>
                    )
                  })}
                  {!(avail.slots || []).length && <div className="col-span-3 text-gray-400 text-xs py-2">No time slots available.</div>}
                </div>
              </div>
            )}
          </section>

          {/* 받는 분 / 주소 (배송) */}
          {fulfillment === 'DELIVERY' && (
            <section className="bg-white rounded-2xl border border-blush-100/60 p-5 space-y-3">
              <div className="text-sm font-semibold">Recipient Information</div>
              <div className="grid grid-cols-2 gap-3">
                <input value={receiverName} onChange={e => setReceiverName(e.target.value)} placeholder="Recipient Name" className="px-3 py-2 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
                <input value={receiverPhone} onChange={e => setReceiverPhone(e.target.value)} placeholder="Phone" className="px-3 py-2 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
              </div>
              <div className="flex gap-2">
                <input value={address} onChange={e => setAddress(e.target.value)} placeholder="Delivery Address" className="flex-1 px-3 py-2 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
                <input value={deliveryZip} onChange={e => setDeliveryZip(e.target.value.replace(/\D/g, '').slice(0, 5))} placeholder="ZIP" className="w-24 px-3 py-2 rounded-xl border border-blush-100 text-sm text-center outline-none focus:border-bloom" />
                <button onClick={verifyAddr} className="px-3 rounded-xl border border-bloom text-bloom text-sm font-semibold flex items-center gap-1"><MapPin size={14} /> Verify</button>
              </div>
              {addrCheck && (
                <div className={`text-xs ${addrCheck.valid ? 'text-leaf' : 'text-blush-500'}`}>
                  {addrCheck.valid ? `Verified: ${addrCheck.normalized || address} (${addrCheck.provider})` : `Address verification failed (${addrCheck.provider})`}
                </div>
              )}
            </section>
          )}

          {/* 카드 메시지 / 메모 */}
          <section className="bg-white rounded-2xl border border-blush-100/60 p-5 space-y-3">
            <div className="flex items-center justify-between"><div className="text-sm font-semibold">Gift Card Message</div><span className="text-xs text-bloom flex items-center gap-1"><Sparkles size={12} /> AI writing is on the product page</span></div>
            <textarea value={cardMessage} onChange={e => setCardMessage(e.target.value)} rows={2} maxLength={200} placeholder="Message for the recipient" className="w-full px-3 py-2 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
            <input value={memo} onChange={e => setMemo(e.target.value)} placeholder="Special Instructions (optional)" className="w-full px-3 py-2 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
          </section>

          {/* 결제수단 (Montvale: Visa·Mastercard·Amex·Discover·Apple Pay·Google Pay) */}
          <section className="bg-white rounded-2xl border border-blush-100/60 p-5">
            <div className="text-sm font-semibold mb-3">Payment Method</div>
            <PaymentSection
              method={payMethod}
              onMethod={setPayMethod}
              onCardChange={setCard}
              cards={BRAND.cards}
              wallets={BRAND.wallets}
            />
          </section>
        </div>

        {/* 요약 */}
        <aside className="bg-white rounded-2xl border border-blush-100/60 p-5 h-fit sticky top-20">
          <div className="text-sm font-semibold mb-3">Order Summary</div>
          <div className="space-y-1.5 text-sm">
            <Row k="Subtotal" v={money(subtotal)} />
            {surge > 0 && <Row k="Surge Pricing" v={`+${money(surge)}`} amber />}
            <Row k="Tax" v={money(taxAmount)} sub={tax ? `${tax.provider} ${(tax.rate * 100).toFixed(1)}%` : ''} />
            {tierDiscount > 0 && <Row k={`Tier Discount (${loyalty?.tierName || ''} ${discountRate}%)`} v={`-${money(tierDiscount)}`} green />}
            {usePointsAmt > 0 && <Row k="Points Used" v={`-${money(usePointsAmt)}`} green />}
          </div>

          {/* 마일리지/포인트 */}
          {!!custToken && (
            <div className="mt-4 bg-petal rounded-xl p-3">
              <div className="flex items-center justify-between text-xs text-bloom2 mb-1">
                <span>Points Balance {pointBalance.toLocaleString()} pts</span>
                <button onClick={() => setUsePointsAmt(maxUsablePoints)} className="text-bloom font-semibold">Use All</button>
              </div>
              <input type="range" min={0} max={maxUsablePoints} value={usePointsAmt} onChange={e => setUsePointsAmt(Number(e.target.value))} className="w-full accent-bloom" />
              <div className="text-xs text-gray-500 text-right">{usePointsAmt.toLocaleString()} pts used</div>
            </div>
          )}

          <div className="border-t border-blush-100/60 mt-4 pt-3 flex justify-between font-bold text-base">
            <span>Order Total</span><span className="text-bloom2">{money(grand)}</span>
          </div>
          {err && <div className="text-blush-500 text-xs mt-3">{err}</div>}
          <button onClick={placeOrder} disabled={placing} className="w-full mt-4 bg-bloom text-white font-semibold py-3 rounded-full hover:bg-bloom2 disabled:opacity-60">
            {placing ? 'Processing…' : `Place Order · ${money(grand)}`}
          </button>
          <p className="text-[11px] text-gray-400 text-center mt-2">Payments processed via GUARDiA PaymentGateway (secure adapter) · Card details not stored</p>
        </aside>
      </div>
    </div>
  )
}

function Row({ k, v, sub, amber, green }: { k: string; v: string; sub?: string; amber?: boolean; green?: boolean }) {
  return (
    <div className="flex justify-between">
      <span className="text-gray-500">{k}{sub && <span className="text-[10px] text-gray-400 ml-1">{sub}</span>}</span>
      <span className={amber ? 'text-amber-600' : green ? 'text-leaf' : 'font-medium'}>{v}</span>
    </div>
  )
}
