import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Package, Flower2 } from 'lucide-react'
import { Link, useNavigate } from 'react-router-dom'
import { getMyOrders, setOrderStatus } from '../api/client'
import { money, useShop } from '../store/shop'
import StatusBadge from '../components/StatusBadge'

export default function Orders() {
  const qc = useQueryClient()
  const nav = useNavigate()
  const { custToken } = useShop()
  const { data: orders } = useQuery({ queryKey: ['my-orders'], queryFn: () => getMyOrders(''), enabled: !!custToken })

  if (!custToken) { nav('/account'); return null }
  const list = orders || []

  const act = async (id: number, status: string) => { await setOrderStatus(id, status).catch(() => {}); qc.invalidateQueries({ queryKey: ['my-orders'] }) }

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <div className="flex items-center gap-2 mb-6"><Package className="text-bloom" size={22} /><h1 className="font-serif text-2xl font-bold text-blush-900">주문 내역</h1></div>
      {!list.length ? (
        <div className="text-center text-gray-400 py-16">주문 내역이 없습니다. <Link to="/category" className="text-bloom">쇼핑하기 →</Link></div>
      ) : (
        <div className="space-y-3">
          {list.map((o: any) => (
            <div key={o.id} className="bg-white rounded-2xl border border-blush-100/60 p-5">
              <div className="flex items-center justify-between mb-2">
                <div className="font-semibold text-sm">{o.orderNo || `주문 #${o.id}`}</div>
                <StatusBadge status={o.status} />
              </div>
              <div className="text-xs text-gray-500 mb-3">{(o.createdAt || '').slice(0, 16).replace('T', ' ')} · {o.fulfillmentType === 'PICKUP' ? '매장 픽업' : '배송'} · {o.scheduledDate} {o.slotLabel}</div>
              <div className="space-y-1.5">
                {(o.items || []).map((it: any) => (
                  <div key={it.id} className="flex items-center gap-3 text-sm">
                    <div className="w-9 h-9 bg-petal rounded-lg flex items-center justify-center"><Flower2 className="text-bloom/40" size={16} /></div>
                    <span className="flex-1">{it.productName || `상품 #${it.productId}`} {it.sizeCode && `· ${it.sizeCode}`} ×{it.quantity}</span>
                    <span className="text-gray-600">{money(it.price || it.unitPrice)}</span>
                  </div>
                ))}
              </div>
              <div className="flex items-center justify-between mt-3 pt-3 border-t border-blush-100/60">
                <span className="font-bold text-bloom2">{money(o.payAmount ?? o.totalAmount)}</span>
                <div className="flex gap-2">
                  {o.status === 'DELIVERED' && <button onClick={() => act(o.id, 'CONFIRMED')} className="text-xs bg-bloom text-white px-3 py-1.5 rounded-full">구매확정</button>}
                  {['PENDING', 'PAID'].includes(o.status) && <button onClick={() => act(o.id, 'CANCELLED')} className="text-xs border border-blush-100 text-blush-400 px-3 py-1.5 rounded-full">주문취소</button>}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
