'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { BadgeCheck, Ban, ExternalLink, Search, UserPlus } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendAdminUser } from '@/lib/backend'
import { adminUserDraftPayload, draftFromAdminUser } from './UserForm'

const levelLabel: Record<string, string> = {
  registered: '注册用户',
  junior: '初级会员',
  senior: '高级会员',
}

const statusLabel: Record<string, string> = {
  active: '正常',
  disabled: '已禁用',
}

const expertStatusLabel: Record<string, string> = {
  submitted: '专家申请待审',
  pending: '专家申请待审',
  rejected: '专家申请驳回',
  approved: '专家申请通过',
  draft: '专家草稿',
  published: '认证专家',
  offline: '专家下线',
}

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

export default function AdminUsersPage() {
  const [users, setUsers] = useState<BackendAdminUser[]>([])
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [loading, setLoading] = useState(false)
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')

  async function reload(nextSearch = search, nextStatus = status) {
    setLoading(true)
    try {
      const result = await backend.adminUsers({ search: nextSearch.trim(), status: nextStatus })
      setUsers(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
  }, [])

  async function toggleStatus(user: BackendAdminUser) {
    try {
      const nextStatus = user.status === 'disabled' ? 'active' : 'disabled'
      await backend.updateAdminUser(user.id, { ...adminUserDraftPayload(draftFromAdminUser(user)), status: nextStatus })
      setSaved(nextStatus === 'disabled' ? '用户已禁用' : '用户已恢复')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '用户状态更新失败')
    }
  }

  return (
    <AdminShell title="用户档案" description="维护前台客户资料、通行证、手机号/微信绑定和账号状态；会员等级只读，订阅请到会员订阅处理。">
      {(saved || error) && (
        <div className={`mb-3 rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || saved}
        </div>
      )}

      <section className="flex h-[calc(100vh-126px)] min-h-[540px] flex-col overflow-hidden border border-line bg-white">
        <form className="shrink-0 flex flex-col gap-2.5 border-b border-line px-3 py-2.5 lg:flex-row 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="搜索手机号、通行证、微信号或姓名"
              className="h-9 w-full rounded-[4px] border border-line pl-9 pr-3 text-sm outline-none focus:border-brand"
            />
          </div>
          <select value={status} onChange={(event) => { setStatus(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>
            <option value="active">正常</option>
            <option value="disabled">已禁用</option>
          </select>
          <button className="h-9 rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white">查询</button>
          <Link href="/admin/users/new" className="inline-flex h-9 items-center justify-center gap-2 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white">
            <UserPlus className="h-4 w-4" />
            新增用户
          </Link>
        </form>

        <div className="min-h-0 flex-1 divide-y divide-line overflow-y-auto">
          {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载用户...</div>}
          {!loading && users.length === 0 && <div className="px-5 py-8 text-sm font-bold text-muted">暂无用户</div>}
          {!loading && users.map((user) => {
            const expertStatus = user.expertProfileStatus || user.expertApplicationStatus || ''
            return (
              <div key={user.id} className="grid gap-3 px-4 py-3 xl:grid-cols-[minmax(260px,1fr)_210px_150px_170px] xl:items-center">
                <Link href={`/admin/users/${encodeURIComponent(user.passportNo || user.id)}`} className="block min-w-0 hover:text-brand">
                  <div className="flex items-center gap-2">
                    <div className="truncate font-extrabold text-ink">{user.displayName || user.phone || user.wechatId || '未命名用户'}</div>
                    <ExternalLink className="h-3.5 w-3.5 shrink-0 text-soft" />
                  </div>
                  <div className="mt-1 text-xs font-bold text-muted">通行证 {user.passportNo} · 手机 {user.phone || '-'} · 微信 {user.wechatId || '-'}</div>
                  <div className="mt-2 flex flex-wrap gap-1.5">
                    <span className="rounded-[4px] bg-bg px-2 py-1 text-[11px] font-bold text-muted">{levelLabel[user.membershipLevel] || user.membershipLevel}</span>
                    <span className={`rounded-[4px] px-2 py-1 text-[11px] font-bold ${user.status === 'disabled' ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>{statusLabel[user.status || 'active']}</span>
                    {expertStatus && <span className="rounded-[4px] bg-brand-light px-2 py-1 text-[11px] font-bold text-brand">{expertStatusLabel[expertStatus] || expertStatus}</span>}
                  </div>
                </Link>
                <div className="text-sm font-bold text-muted">
                  <div>机构：{user.organization || '-'}</div>
                  <div className="mt-1">职务：{user.title || '-'}</div>
                  <div className="mt-1">城市：{user.city || '-'}</div>
                </div>
                <div className="text-xs font-bold text-muted">
                  <div>订单：{user.orderCount || 0}</div>
                  <div className="mt-1">任务：{user.taskCount || 0}</div>
                  <div className="mt-1">服务：{(user.consultingCount || 0) + (user.dataServiceCount || 0)}</div>
                </div>
                <div className="flex flex-col gap-2 xl:items-end">
                  <div className="text-xs font-bold text-muted">
                    <div>创建：{formatDate(user.createdAt)}</div>
                    <div className="mt-1">登录：{formatDate(user.lastLoginAt)}</div>
                  </div>
                  <button type="button" onClick={() => void toggleStatus(user)} className="inline-flex h-8 w-fit items-center gap-1 rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
                    {user.status === 'disabled' ? <BadgeCheck className="h-3.5 w-3.5" /> : <Ban className="h-3.5 w-3.5" />}
                    {user.status === 'disabled' ? '恢复' : '禁用'}
                  </button>
                </div>
              </div>
            )
          })}
        </div>
      </section>
    </AdminShell>
  )
}
