import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Crown, Coins } from 'lucide-react'
import { getTiers, updateTier, adjustPoints } from '../api/client'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

export default function Loyalty() {
  const qc = useQueryClient()
  const { data: tiers } = useQuery({ queryKey: ['tiers-all'], queryFn: () => getTiers(false) })
  const [edit, setEdit] = useState<any>(null)
  // 포인트 수동 조정
  const [owner, setOwner] = useState('')
  const [points, setPoints] = useState(0)
  const [reason, setReason] = useState('')
  const [adjMsg, setAdjMsg] = useState('')

  const save = async () => {
    if (!edit) return
    await updateTier(edit.id, edit).catch(() => {})
    setEdit(null); qc.invalidateQueries({ queryKey: ['tiers-all'] })
  }
  const doAdjust = async () => {
    if (!owner || !points) return
    const r = await adjustPoints(owner, points, reason).catch(() => null)
    setAdjMsg(r ? `${owner} points adjusted · Balance ${r.balance}P` : 'Adjustment failed')
    setOwner(''); setPoints(0); setReason('')
  }

  return (
    <div>
      <div className="flex items-center gap-2 mb-5"><Crown className="text-brand" size={22} /><h1 className="text-xl font-bold">Tier & Points Management</h1></div>

      <div className="bg-card border border-edge rounded-xl overflow-hidden mb-6">
        <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">Tier</th><th className="text-right">Min Spend</th><th className="text-right">Min Orders</th>
            <th className="text-right">Discount</th><th className="text-right">Earn Rate</th><th className="text-right">Free Shipping</th><th className="text-center">Priority Slot</th><th className="text-center">Edit</th>
          </tr></thead>
          <tbody>
            {(tiers || []).map((t: any) => (
              <tr key={t.id} className="border-b border-edge/50">
                <td className="p-3"><StatusBadge status={t.tierCode} /> <span className="text-slate-400 text-xs ml-1">{t.name}</span></td>
                <td className="text-right">{money(t.minSpend12m)}</td>
                <td className="text-right text-slate-400">{t.minOrders12m}</td>
                <td className="text-right">{t.discountRate}%</td>
                <td className="text-right">{t.pointEarnRate}%</td>
                <td className="text-right text-slate-400">{t.freeShipThreshold === 0 ? 'Always' : t.freeShipThreshold ? money(t.freeShipThreshold) : 'None'}</td>
                <td className="text-center">{t.prioritySlot ? '✓' : '–'}</td>
                <td className="text-center"><button onClick={() => setEdit({ ...t })} className="text-xs text-brand">Edit</button></td>
              </tr>
            ))}
            {!(tiers || []).length && <tr><td colSpan={8} className="text-center text-slate-500 py-8">No tier data found.</td></tr>}
          </tbody>
        </table>
      </div>

      {edit && (
        <div className="bg-card border border-edge rounded-xl p-5 mb-6">
          <div className="text-sm font-semibold mb-3">Edit Tier: {edit.name} ({edit.tierCode})</div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
            <Field label="Min Spend ($)" value={edit.minSpend12m} onChange={v => setEdit({ ...edit, minSpend12m: Number(v) })} />
            <Field label="Min Orders" value={edit.minOrders12m} onChange={v => setEdit({ ...edit, minOrders12m: Number(v) })} />
            <Field label="Discount (%)" value={edit.discountRate} onChange={v => setEdit({ ...edit, discountRate: Number(v) })} />
            <Field label="Earn Rate (%)" value={edit.pointEarnRate} onChange={v => setEdit({ ...edit, pointEarnRate: Number(v) })} />
          </div>
          <div className="flex gap-2 mt-4">
            <button onClick={save} className="bg-brand text-ink font-semibold px-5 py-2 rounded-lg text-sm">Save</button>
            <button onClick={() => setEdit(null)} className="border border-edge px-5 py-2 rounded-lg text-sm text-slate-400">Cancel</button>
          </div>
        </div>
      )}

      <div className="bg-card border border-edge rounded-xl p-5">
        <div className="flex items-center gap-2 text-sm font-semibold mb-3"><Coins size={16} className="text-brand" /> Manual Point Adjustment</div>
        <div className="grid grid-cols-4 gap-3">
          <input value={owner} onChange={e => setOwner(e.target.value)} placeholder="Customer ID" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <input type="number" value={points || ''} onChange={e => setPoints(Number(e.target.value))} placeholder="Points (+/-)" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <input value={reason} onChange={e => setReason(e.target.value)} placeholder="Reason" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <button onClick={doAdjust} className="bg-brand2 text-white rounded-lg px-3 py-2 text-sm font-semibold">Adjust</button>
        </div>
        {adjMsg && <div className="text-xs text-accent mt-2">{adjMsg}</div>}
      </div>
    </div>
  )
}

function Field({ label, value, onChange }: { label: string; value: any; onChange: (v: string) => void }) {
  return (
    <div>
      <label className="block text-[11px] text-slate-400 mb-1">{label}</label>
      <input value={value} onChange={e => onChange(e.target.value)} className="w-full bg-panel border border-edge rounded-lg px-3 py-2" />
    </div>
  )
}
