'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { RefreshCw, Save, ShieldCheck } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendPermissionItem, type BackendStaffAccount, type BackendStaffRole } from '@/lib/backend'

function groupPermissions(items: BackendPermissionItem[]) {
  return [...items].sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0)).reduce<Record<string, BackendPermissionItem[]>>((groups, item) => {
    const key = `${item.group}${item.module ? ` / ${item.module}` : ''}`
    groups[key] = [...(groups[key] || []), item]
    return groups
  }, {})
}

const familyLabel: Record<string, string> = {
  system: '系统管理',
  operations: '运营中心',
  fulfillment: '履约中心',
  content: '内容中心',
  finance: '财务中心',
}

function groupRoles(roles: BackendStaffRole[]) {
  return roles.reduce<Record<string, BackendStaffRole[]>>((groups, role) => {
    const family = role.roleFamily || 'operations'
    groups[family] = [...(groups[family] || []), role]
    return groups
  }, {})
}

function isSuperRole(role?: BackendStaffRole | null) {
  return role?.code === 'super_admin'
}

export default function AdminStaffRolesPage() {
  const [roles, setRoles] = useState<BackendStaffRole[]>([])
  const [catalog, setCatalog] = useState<BackendPermissionItem[]>([])
  const [roleAccounts, setRoleAccounts] = useState<BackendStaffAccount[]>([])
  const [selectedCode, setSelectedCode] = useState('')
  const [draft, setDraft] = useState<BackendStaffRole | null>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')

  const groupedCatalog = useMemo(() => groupPermissions(catalog), [catalog])
  const groupedRoles = useMemo(() => groupRoles(roles), [roles])

  async function reload(nextSelected = selectedCode) {
    setLoading(true)
    try {
      const [roleResult, catalogResult] = await Promise.all([
        backend.adminStaffRoles(),
        backend.adminPermissionCatalog(),
      ])
      setRoles(roleResult.items)
      setCatalog(catalogResult.items)
      const nextCode = nextSelected || roleResult.items[0]?.code || ''
      const selected = roleResult.items.find((item) => item.code === nextCode) || roleResult.items[0] || null
      setSelectedCode(selected?.code || '')
      setDraft(selected ? { ...selected, permissions: [...selected.permissions] } : null)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '角色与权限加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  useEffect(() => {
    if (!selectedCode) {
      setRoleAccounts([])
      return
    }
    backend.adminStaffRoleAccounts(selectedCode)
      .then((result) => setRoleAccounts(result.items))
      .catch(() => setRoleAccounts([]))
  }, [selectedCode])

  function selectRole(role: BackendStaffRole) {
    setSelectedCode(role.code)
    setDraft({ ...role, permissions: [...role.permissions] })
    setSaved('')
    setError('')
  }

  function togglePermission(code: string) {
    if (!draft || isSuperRole(draft)) return
    const current = new Set(draft.permissions)
    if (current.has(code)) current.delete(code)
    else current.add(code)
    current.delete('*')
    setDraft({ ...draft, permissions: Array.from(current) })
  }

  async function saveRole() {
    if (!draft) return
    setSaving(true)
    setSaved('')
    setError('')
    try {
      const updated = await backend.updateAdminStaffRole(draft.code, {
        name: draft.name,
        description: draft.description,
        defaultEntry: draft.defaultEntry,
        status: isSuperRole(draft) ? 'active' : draft.status,
        permissions: isSuperRole(draft) ? ['*'] : draft.permissions,
      })
      setSaved('岗位权限已保存')
      await reload(updated.code)
    } catch (err) {
      setError(err instanceof Error ? err.message : '岗位权限保存失败')
    } finally {
      setSaving(false)
    }
  }

  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>
      )}

      <div className="mb-3 flex justify-end">
        <button type="button" onClick={() => void reload()} className="inline-flex h-9 items-center gap-2 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
          <RefreshCw className="h-4 w-4" />
          刷新
        </button>
      </div>

      <div className="grid gap-4 xl:grid-cols-[300px_minmax(0,1fr)]">
        <aside className="border border-line bg-white">
          <div className="border-b border-line px-4 py-3">
            <h2 className="font-extrabold text-ink">角色模板</h2>
          </div>
          {loading && <div className="px-4 py-8 text-sm font-bold text-muted">正在加载岗位...</div>}
          {!loading && Object.entries(groupedRoles).map(([family, familyRoles]) => (
            <div key={family} className="border-b border-line">
              <div className="bg-bg px-4 py-2 text-[11px] font-extrabold text-soft">{familyLabel[family] || family}</div>
              {familyRoles.map((role) => (
                <button key={role.code} type="button" onClick={() => selectRole(role)} className={`block w-full border-t border-line px-4 py-3 text-left ${selectedCode === role.code ? 'bg-ink text-white' : 'hover:bg-bg'}`}>
                  <div className="flex items-center justify-between gap-3">
                    <div className="font-extrabold">{role.name}</div>
                    <span className={`text-[11px] font-bold ${selectedCode === role.code ? 'text-white/70' : role.status === 'disabled' ? 'text-red-600' : 'text-green'}`}>{role.status === 'disabled' ? '停用' : '启用'}</span>
                  </div>
                  <div className={`mt-1 text-xs font-bold ${selectedCode === role.code ? 'text-white/70' : 'text-muted'}`}>L{role.roleLevel || 50} · {role.activeStaffCount || 0}/{role.staffCount || 0} 人启用</div>
                </button>
              ))}
            </div>
          ))}
        </aside>

        <section className="border border-line bg-white">
          {!draft ? (
            <div className="px-5 py-12 text-center text-sm font-bold text-muted">请选择角色模板</div>
          ) : (
            <>
              <div className="border-b border-line px-5 py-4">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <div className="flex items-center gap-2">
                      <ShieldCheck className="h-4 w-4 text-brand" />
                      <h2 className="text-base font-extrabold text-ink">{draft.name}</h2>
                    </div>
                    <div className="mt-1 text-xs font-bold text-muted">{familyLabel[draft.roleFamily || ''] || draft.roleFamily || '未分组'} · L{draft.roleLevel || 50} · 默认入口 {draft.defaultEntry} · 权限 {isSuperRole(draft) ? '全部' : draft.permissions.length}</div>
                  </div>
                  <button type="button" onClick={() => void saveRole()} disabled={saving} className="inline-flex h-9 items-center gap-2 rounded-[4px] bg-brand px-3 text-xs font-extrabold text-white hover:bg-brand-dark disabled:bg-line-dark">
                    <Save className="h-4 w-4" />
                    {saving ? '保存中...' : '保存权限'}
                  </button>
                </div>
              </div>

              <div className="grid gap-4 px-5 py-5 lg:grid-cols-2">
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">岗位名称</span>
                  <input value={draft.name} onChange={(event) => setDraft({ ...draft, name: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">默认入口</span>
                  <input value={draft.defaultEntry} onChange={(event) => setDraft({ ...draft, defaultEntry: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">状态</span>
                  <select value={isSuperRole(draft) ? 'active' : draft.status} disabled={isSuperRole(draft)} onChange={(event) => setDraft({ ...draft, status: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand disabled:bg-bg disabled:text-soft">
                    <option value="active">启用</option>
                    <option value="disabled">停用</option>
                  </select>
                </label>
                <div className="grid grid-cols-2 gap-2">
                  <div className="border border-line bg-bg px-3 py-2">
                    <div className="text-[11px] font-bold text-soft">角色层级</div>
                    <div className="mt-1 text-xl font-extrabold text-ink">L{draft.roleLevel || 50}</div>
                  </div>
                  <div className="border border-line bg-bg px-3 py-2">
                    <div className="text-[11px] font-bold text-soft">启用/总员工</div>
                    <div className="mt-1 text-xl font-extrabold text-ink">{draft.activeStaffCount || 0}/{draft.staffCount || 0}</div>
                  </div>
                </div>
                <label className="block lg:col-span-2">
                  <span className="mb-2 block text-sm font-bold text-ink">说明</span>
                  <textarea value={draft.description} onChange={(event) => setDraft({ ...draft, description: event.target.value })} className="min-h-[84px] w-full rounded-[4px] border border-line px-3 py-2 text-sm outline-none focus:border-brand" />
                </label>
              </div>

              <div className="border-t border-line px-5 py-5">
                <h3 className="mb-3 text-sm font-extrabold text-ink">权限矩阵</h3>
                {isSuperRole(draft) ? (
                  <div className="rounded-[4px] bg-brand-light px-4 py-3 text-sm font-bold text-brand">超级管理员固定拥有全部权限，不支持移除。</div>
                ) : (
                  <div className="grid gap-4 xl:grid-cols-2">
                    {Object.entries(groupedCatalog).map(([group, permissions]) => (
                      <section key={group} className="border border-line">
                        <div className="border-b border-line bg-bg px-3 py-2 text-sm font-extrabold text-ink">{group}</div>
                        <div className="divide-y divide-line">
                          {permissions.filter((permission) => permission.code !== '*').map((permission) => (
                            <label key={permission.code} className="grid cursor-pointer grid-cols-[18px_1fr] gap-3 px-3 py-3 hover:bg-bg">
                              <input type="checkbox" checked={draft.permissions.includes(permission.code)} onChange={() => togglePermission(permission.code)} className="mt-1 h-4 w-4 accent-brand" />
                              <span className="min-w-0">
                                <span className="block text-sm font-extrabold text-ink">{permission.label}</span>
                                <span className="mt-1 block text-xs font-bold leading-5 text-muted">{permission.description}</span>
                                <span className="mt-1 block text-[11px] font-bold text-soft">{permission.code}</span>
                              </span>
                            </label>
                          ))}
                        </div>
                      </section>
                    ))}
                  </div>
                )}
              </div>

              <div className="border-t border-line px-5 py-5">
                <h3 className="mb-3 text-sm font-extrabold text-ink">影响员工</h3>
                {roleAccounts.length === 0 ? (
                  <div className="rounded-[4px] bg-bg px-4 py-3 text-sm font-bold text-muted">当前没有员工使用该角色。</div>
                ) : (
                  <div className="grid gap-2 md:grid-cols-2 xl:grid-cols-3">
                    {roleAccounts.slice(0, 12).map((item) => (
                      <Link key={item.id} href={`/admin/staff-accounts/${item.id}`} className="border border-line px-3 py-2 hover:border-brand">
                        <div className="truncate text-sm font-extrabold text-ink">{item.displayName}</div>
                        <div className="mt-1 truncate text-xs font-bold text-muted">{item.phone || item.email || '-'} · {item.status === 'disabled' ? '禁用' : '启用'}</div>
                      </Link>
                    ))}
                    {roleAccounts.length > 12 && <div className="border border-dashed border-line px-3 py-2 text-sm font-bold text-muted">还有 {roleAccounts.length - 12} 名员工使用该角色</div>}
                  </div>
                )}
              </div>
            </>
          )}
        </section>
      </div>
    </AdminShell>
  )
}
