'use client'

import { useEffect, useMemo, useState } from 'react'
import { Activity, RefreshCw, Search } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendStaffAuditLog } from '@/lib/backend'

const actionLabel: Record<string, string> = {
  'staff.login.password': '账号密码登录',
  'staff.login.phone': '手机号登录',
  'staff_account.create': '新增员工',
  'staff_account.update': '更新员工',
  'staff_assignment.upsert': '设置员工归属',
  'staff_role.update': '更新角色权限',
  'event.checkin': '活动核销',
  'course.checkin': '课程核销',
  'membership.manual_grant': '手动开通会员',
  'membership.period_end': '到期不续',
  'membership.immediate': '立即关闭会员',
  'membership.assign_manager': '分配客户经理',
  'membership.expiry_reconcile': '会员过期校准',
  'membership.expiry_reminders': '到期提醒生成',
  'membership.winback_reminders': '流失提醒生成',
  'notification.dispatch': '派发站内消息',
}

const sourceLabel: Record<string, string> = {
  staff: '员工',
  admin: '后台',
}

function formatDate(value?: string | null) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN')
}

export default function AdminStaffAuditPage() {
  const [items, setItems] = useState<BackendStaffAuditLog[]>([])
  const [search, setSearch] = useState('')
  const [action, setAction] = useState('')
  const [source, setSource] = useState('')
  const [targetType, setTargetType] = useState('')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [selected, setSelected] = useState<BackendStaffAuditLog | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const actions = useMemo(() => Array.from(new Set(items.map((item) => item.action).filter(Boolean))), [items])

  async function reload(nextSearch = search, nextAction = action) {
    setLoading(true)
    try {
      const result = await backend.adminStaffAuditLogs({
        search: nextSearch.trim(),
        action: nextAction,
        source,
        targetType,
        dateFrom,
        dateTo,
      })
      setItems(result.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作记录加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void reload('', '')
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <AdminShell title="操作审计" description="只读查看后台和员工侧关键操作，可按来源、动作、对象和时间追溯。">
      {error && <div className="mb-3 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

      <form className="mb-2 flex flex-col gap-2.5 border border-line bg-white px-3 py-2.5 lg:flex-row lg:flex-wrap lg:items-center" onSubmit={(event) => { event.preventDefault(); void reload() }}>
        <div className="relative min-w-0 flex-1">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-soft" />
          <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索操作者、动作、摘要、对象 ID" className="h-9 w-full rounded-[4px] border border-line pl-9 pr-3 text-sm outline-none focus:border-brand" />
        </div>
        <select value={action} onChange={(event) => { setAction(event.target.value); void reload(search, event.target.value) }} className="h-9 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
          <option value="">全部动作</option>
          {actions.map((item) => <option key={item} value={item}>{actionLabel[item] || item}</option>)}
        </select>
        <select value={source} onChange={(event) => setSource(event.target.value)} className="h-9 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
          <option value="">全部来源</option>
          <option value="staff">员工侧</option>
          <option value="admin">后台</option>
        </select>
        <input value={targetType} onChange={(event) => setTargetType(event.target.value)} placeholder="对象类型" className="h-9 w-32 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
        <input value={dateFrom} onChange={(event) => setDateFrom(event.target.value)} type="date" className="h-9 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
        <input value={dateTo} onChange={(event) => setDateTo(event.target.value)} type="date" className="h-9 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
        <button className="h-9 rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white">查询</button>
        <button type="button" onClick={() => void reload()} className="inline-flex h-9 items-center justify-center gap-2 rounded-[4px] border border-line px-4 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">
          <RefreshCw className="h-4 w-4" />
          刷新
        </button>
      </form>

      <section className="grid h-[calc(100vh-162px)] min-h-[540px] overflow-hidden border border-line bg-white xl:grid-cols-[minmax(0,1fr)_360px]">
        <div className="min-h-0 flex flex-col overflow-hidden">
        <div className="grid shrink-0 grid-cols-[160px_180px_minmax(260px,1fr)_180px] border-b border-line px-3 py-2.5 text-xs font-extrabold text-soft">
          <span>时间</span><span>操作者</span><span>动作摘要</span><span>对象</span>
        </div>
        <div className="min-h-0 flex-1 overflow-y-auto">
          {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载操作记录...</div>}
          {!loading && items.length === 0 && <div className="px-5 py-8 text-sm font-bold text-muted">暂无操作记录</div>}
          {!loading && items.map((item) => (
          <button key={item.id} type="button" onClick={() => setSelected(item)} className={`grid w-full grid-cols-[160px_180px_minmax(260px,1fr)_180px] items-start border-b border-line px-3 py-3 text-left text-sm hover:bg-bg ${selected?.id === item.id ? 'bg-bg' : ''}`}>
            <div className="text-xs font-bold text-muted">{formatDate(item.createdAt)}</div>
            <div className="min-w-0">
              <div className="truncate font-extrabold text-ink">{item.actorName || item.actorEmail || '-'}</div>
              <div className="mt-1 truncate text-xs font-bold text-soft">{item.actorEmail || '-'}</div>
            </div>
            <div className="min-w-0">
              <div className="flex items-center gap-2 font-extrabold text-ink">
                <Activity className="h-4 w-4 shrink-0 text-brand" />
                <span className="rounded-[4px] bg-bg px-1.5 py-0.5 text-[10px] font-extrabold text-soft">{sourceLabel[item.source || ''] || item.source || '-'}</span>
                <span>{actionLabel[item.action] || item.action}</span>
              </div>
              <div className="mt-1 break-words text-xs font-bold leading-5 text-muted">{item.summary || '-'}</div>
            </div>
            <div className="min-w-0 text-xs font-bold text-muted">
              <div>{item.targetType}</div>
              <div className="mt-1 truncate text-soft">{item.targetId || '-'}</div>
            </div>
          </button>
          ))}
        </div>
        </div>
        <aside className="min-h-0 overflow-y-auto border-l border-line bg-bg p-3">
          <div className="mb-2 text-sm font-extrabold text-ink">审计详情</div>
          {!selected ? (
            <div className="border border-dashed border-line bg-white px-3 py-8 text-center text-sm font-bold text-muted">点击左侧记录查看 metadata</div>
          ) : (
            <div className="space-y-2 text-xs font-bold text-muted">
              <div className="border border-line bg-white p-3">
                <div className="text-sm font-extrabold text-ink">{actionLabel[selected.action] || selected.action}</div>
                <div className="mt-1">{formatDate(selected.createdAt)}</div>
                <div className="mt-1">{selected.targetType} · {selected.targetId || '-'}</div>
              </div>
              <pre className="max-h-[420px] overflow-auto border border-line bg-white p-3 text-[11px] leading-5 text-ink">{JSON.stringify(selected.metadata || {}, null, 2)}</pre>
            </div>
          )}
        </aside>
      </section>
    </AdminShell>
  )
}
