import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Flower2, Search } from 'lucide-react'
import { getProducts, setProductStatus } from '../api/client'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

export default function Products() {
  const qc = useQueryClient()
  const [kw, setKw] = useState('')
  const { data } = useQuery({ queryKey: ['admin-products', kw], queryFn: () => getProducts({ keyword: kw, size: 100, status: '' }) })
  const items = data?.items || []

  const cycle = async (id: number, status: string) => {
    const next = status === 'ACTIVE' ? 'HIDDEN' : 'ACTIVE'
    await setProductStatus(id, next).catch(() => {}); qc.invalidateQueries({ queryKey: ['admin-products'] })
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><Flower2 className="text-brand" size={22} /><h1 className="text-xl font-bold">상품 관리</h1></div>
        <div className="flex items-center gap-2 bg-card border border-edge rounded-lg px-3 py-2">
          <Search size={15} className="text-slate-500" />
          <input value={kw} onChange={e => setKw(e.target.value)} placeholder="상품 검색" className="bg-transparent text-sm outline-none w-48" />
        </div>
      </div>
      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="text-slate-400 text-xs border-b border-edge bg-panel">
            <th className="text-left p-3">SKU</th><th className="text-left">상품명</th><th className="text-left">상황</th>
            <th className="text-right">가격</th><th className="text-right">재고</th><th className="text-right">판매</th><th className="text-right">평점</th><th className="text-center">상태</th>
          </tr></thead>
          <tbody>
            {items.map((p: any) => (
              <tr key={p.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 font-mono text-xs text-slate-400">{p.sku}</td>
                <td>{p.name}</td>
                <td className="text-slate-400">{p.occasion || '-'}</td>
                <td className="text-right">{money(p.salePrice && p.salePrice > 0 ? p.salePrice : p.price)}</td>
                <td className="text-right text-slate-400">{p.stock}</td>
                <td className="text-right text-slate-400">{p.salesCount}</td>
                <td className="text-right text-amber-400">{p.ratingAvg?.toFixed(1) || '-'}</td>
                <td className="text-center"><button onClick={() => cycle(p.id, p.status)}><StatusBadge status={p.status} /></button></td>
              </tr>
            ))}
            {!items.length && <tr><td colSpan={8} className="text-center text-slate-500 py-8">상품이 없습니다.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
