'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { BadgeCheck, Ban, ExternalLink, Search, UserPlus } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendOrgTree, type BackendStaffAccount, type BackendStaffRole } from '@/lib/backend'

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

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

function responsibilityCount(item: BackendStaffAccount) {
  return (item.taskCount || 0) + (item.consultingCount || 0) + (item.dataServiceCount || 0) + (item.checkinCount || 0)
}

export default function AdminStaffAccountsPage() {
  const [items, setItems] = useState<BackendStaffAccount[]>([])
  const [roles, setRoles] = useState<BackendStaffRole[]>([])
  const [orgTree, setOrgTree] = useState<BackendOrgTree>({ units: [], positions: [], assignments: [] })
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [role, setRole] = useState('')
  const [orgUnitId, setOrgUnitId] = useState('')
  const [positionId, setPositionId] = useState('')
  const [loading, setLoading] = useState(true)
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')

  const summary = useMemo(() => ({
    total: items.length,
    active: items.filter((item) => item.status === 'active').length,
    disabled: items.filter((item) => item.status === 'disabled').length,
  }), [items])
  const unitById = useMemo(() => new Map(orgTree.units.map((item) => [item.id, item.name])), [orgTree.units])
  const positionById = useMemo(() => new Map(orgTree.positions.map((item) => [item.id, item.name])), [orgTree.positions])
  const filteredItems = useMemo(() => items.filter((item) => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    if (positionId && item.positionId !== positionId) return false
    return true
  }), [items, orgUnitId, positionId])
  const positionOptions = useMemo(
    () => orgTree.positions.filter((item) => !orgUnitId || item.orgUnitId === orgUnitId),
    [orgTree.positions, orgUnitId],
  )

  async function reload(nextSearch = search, nextStatus = status, nextRole = role) {
    setLoading(true)
    try {
      const [accountResult, roleResult, orgResult] = await Promise.all([
        backend.adminStaffAccounts({ search: nextSearch.trim(), status: nextStatus, role: nextRole }),
        backend.adminStaffRoles(),
        backend.adminOrgTree(),
      ])
      setItems(accountResult.items)
      setRoles(roleResult.items)
      setOrgTree(orgResult)
      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(item: BackendStaffAccount) {
    try {
      const next = item.status === 'disabled'
        ? await backend.enableAdminStaffAccount(item.id)
        : await backend.disableAdminStaffAccount(item.id)
      setSaved(next.status === 'disabled' ? '员工已禁用' : '员工已恢复')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '员工状态更新失败')
    }
  }

  return (
    <AdminShell
      title="员工账号"
      description="管理后台登录人员、部门岗位归属和账号状态；前台客户请到用户档案维护。"
      topbarMetrics={[
        { label: '内部人员', value: summary.total },
        { label: '启用账号', value: summary.active },
        { label: '禁用账号', value: summary.disabled },
      ]}
    >
      {(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-170px)] min-h-[520px] 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={orgUnitId} onChange={(event) => { setOrgUnitId(event.target.value); setPositionId('') }} className="h-9 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
            <option value="">全部部门</option>
            {orgTree.units.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
          </select>
          <select value={positionId} onChange={(event) => setPositionId(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>
            {positionOptions.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
          </select>
          <select value={role} onChange={(event) => { setRole(event.target.value); void reload(search, status, 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>
            {roles.map((item) => <option key={item.code} value={item.code}>{item.name}</option>)}
          </select>
          <select value={status} onChange={(event) => { setStatus(event.target.value); void reload(search, event.target.value, role) }} 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/staff-accounts/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 && filteredItems.length === 0 && <div className="px-5 py-8 text-sm font-bold text-muted">暂无员工账号</div>}
          {!loading && filteredItems.map((item) => (
            <div key={item.id} className="grid gap-3 px-4 py-3 xl:grid-cols-[minmax(260px,1fr)_170px_190px_160px] xl:items-center">
              <Link href={`/admin/staff-accounts/${item.id}`} className="min-w-0 hover:text-brand">
                <div className="flex items-center gap-2">
                  <div className="truncate font-extrabold text-ink">{item.displayName}</div>
                  <ExternalLink className="h-3.5 w-3.5 shrink-0 text-soft" />
                </div>
                <div className="mt-1 text-xs font-bold text-muted">手机号 {item.phone || '-'} · 验证码登录</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">{unitById.get(item.orgUnitId || '') || '未分配部门'}</span>
                  <span className="rounded-[4px] bg-bg px-2 py-1 text-[11px] font-bold text-muted">{positionById.get(item.positionId || '') || '未分配岗位'}</span>
                  <span className="rounded-[4px] bg-bg px-2 py-1 text-[11px] font-bold text-muted">{item.roleName || item.role}</span>
                  <span className={`rounded-[4px] px-2 py-1 text-[11px] font-bold ${item.status === 'disabled' ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>{statusLabel[item.status] || item.status}</span>
                  {item.positionTitle && <span className="rounded-[4px] bg-brand-light px-2 py-1 text-[11px] font-bold text-brand">{item.positionTitle}</span>}
                </div>
              </Link>
              <div className="text-xs font-bold text-muted">
                <div>任务：{item.taskCount || 0}</div>
                <div className="mt-1">咨询：{item.consultingCount || 0}</div>
                <div className="mt-1">数据：{item.dataServiceCount || 0}</div>
                <div className="mt-1">核销：{item.checkinCount || 0}</div>
              </div>
              <div className="text-xs font-bold text-muted">
                <div>最近登录：{formatDate(item.lastLoginAt)}</div>
                <div className="mt-1">更新时间：{formatDate(item.updatedAt)}</div>
                <div className="mt-1">负责事项：{responsibilityCount(item)}</div>
              </div>
              <div className="flex flex-col gap-2 xl:items-end">
                <Link href={`/admin/staff-accounts/${item.id}`} className="inline-flex h-8 w-fit items-center rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">详情</Link>
                <button type="button" onClick={() => void toggleStatus(item)} 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">
                  {item.status === 'disabled' ? <BadgeCheck className="h-3.5 w-3.5" /> : <Ban className="h-3.5 w-3.5" />}
                  {item.status === 'disabled' ? '恢复' : '禁用'}
                </button>
              </div>
            </div>
          ))}
        </div>
      </section>
    </AdminShell>
  )
}
