import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Users, RefreshCw, Search } from 'lucide-react'
import { getLoyaltyByTier, recalcAllLoyalty, getAdminMembers } from '../api/client'
import Chart from '../components/Chart'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

const TIERS = ['', 'STANDARD', 'BASIC', 'SILVER', 'GOLD', 'VIP']

export default function Members() {
  const qc = useQueryClient()
  const [kw, setKw] = useState('')
  const [tier, setTier] = useState('')
  const { data: byTier } = useQuery({ queryKey: ['by-tier'], queryFn: () => getLoyaltyByTier(30) })
  const { data: members } = useQuery({ queryKey: ['admin-members', kw, tier], queryFn: () => getAdminMembers(kw, tier, 200) })

  const recalc = async () => { await recalcAllLoyalty().catch(() => {}); qc.invalidateQueries({ queryKey: ['by-tier'] }) }
  const rows = (byTier || []).map((t: any) => ({ name: t.tier, customers: t.customers, sales: t.sales }))
  const list = members?.items || []

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><Users className="text-brand" size={22} /><h1 className="text-xl font-bold">Members (CRM)</h1></div>
        <button onClick={recalc} className="flex items-center gap-1.5 bg-card border border-edge text-sm px-3 py-2 rounded-lg text-slate-300 hover:text-brand"><RefreshCw size={14} /> Recalculate All Tiers</button>
      </div>

      <div className="grid lg:grid-cols-2 gap-5 mb-5">
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">Customer Distribution by Tier (30 days)</h2>
          <Chart type="BAR" rows={rows} dataKeys={['customers']} />
        </div>
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">Sales Contribution by Tier</h2>
          <Chart type="PIE" rows={(byTier || []).map((t: any) => ({ name: t.tier, value: t.sales }))} dataKeys={['value']} />
        </div>
      </div>

      <div className="bg-card border border-edge rounded-xl p-5 mb-5">
        <h2 className="text-sm font-semibold mb-3">Tier Summary</h2>
        <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">Customers</th><th className="text-right">Orders</th><th className="text-right">Sales</th>
          </tr></thead>
          <tbody>
            {(byTier || []).map((t: any) => (
              <tr key={t.tier} className="border-b border-edge/50">
                <td className="p-3"><StatusBadge status={t.tier} /></td>
                <td className="text-right">{t.customers}</td>
                <td className="text-right text-slate-400">{t.orderCount}</td>
                <td className="text-right">{money(t.sales)}</td>
              </tr>
            ))}
            {!(byTier || []).length && <tr><td colSpan={4} className="text-center text-slate-500 py-8">No data</td></tr>}
          </tbody>
        </table>
      </div>

      {/* 회원 목록/검색 — PII(이메일·전화)는 마스킹된 값만 표시 */}
      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <div className="flex items-center justify-between p-4 border-b border-edge">
          <h2 className="text-sm font-semibold">Member List <span className="text-slate-500 font-normal">({members?.total ?? 0})</span></h2>
          <div className="flex items-center gap-2">
            <select value={tier} onChange={e => setTier(e.target.value)} className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm">
              {TIERS.map(t => <option key={t} value={t}>{t || 'All Tiers'}</option>)}
            </select>
            <div className="flex items-center gap-2 bg-panel 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="Search by name or ID" className="bg-transparent text-sm outline-none w-48" />
            </div>
          </div>
        </div>
        <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">Customer</th><th className="text-left">Email</th><th className="text-left">Phone</th>
            <th className="text-left">ZIP</th><th className="text-center">Tier</th><th className="text-right">Orders</th><th className="text-right">Lifetime Value</th><th className="text-left">Joined</th>
          </tr></thead>
          <tbody>
            {list.map((m: any) => (
              <tr key={m.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3">
                  <div className="font-medium">{m.displayName || m.username}</div>
                  <div className="text-xs text-slate-500 font-mono">@{m.username}</div>
                </td>
                <td className="text-slate-400">{m.emailMasked || '-'}</td>
                <td className="text-slate-400">{m.phoneMasked || '-'}</td>
                <td className="text-slate-400">{m.defaultZip || '-'}</td>
                <td className="text-center"><StatusBadge status={m.tier} /></td>
                <td className="text-right text-slate-400">{m.orderCount}</td>
                <td className="text-right">{money(m.totalSpent)}</td>
                <td className="text-slate-400 text-xs">{m.createdAt ? String(m.createdAt).slice(0, 10) : '-'}</td>
              </tr>
            ))}
            {!list.length && <tr><td colSpan={8} className="text-center text-slate-500 py-8">No members found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
