import { useEffect, useState, useCallback } from 'react'
import { Navigate } from 'react-router-dom'
import { fetchUsers, updateUserRole, deleteUser } from '../services/api.js'
import { useAuth } from '../contexts/AuthContext.jsx'

const SUPER_ADMIN_EMAIL = '494161546@qq.com'
const SUPER_ADMIN_PHONE = '13136092523'

function fmtTime(val) {
  if (!val) return '—'
  const d = new Date(typeof val === 'number' ? val * 1000 : val)
  if (isNaN(d.getTime())) return '—'
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

export default function UserManagement() {
  const { user } = useAuth()
  const isAdmin = user?.email === SUPER_ADMIN_EMAIL || user?.phone === SUPER_ADMIN_PHONE

  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [searchInput, setSearchInput] = useState('')
  const [searchKeyword, setSearchKeyword] = useState('')
  const [confirmAction, setConfirmAction] = useState(null) // { type: 'role'|'delete', user, newRole? }

  const loadUsers = useCallback(async (q = '') => {
    setLoading(true)
    setError('')
    try {
      const r = await fetchUsers(q)
      setUsers(Array.isArray(r?.data) ? r.data : [])
    } catch (e) {
      const detail = e?.response?.data?.message || e?.response?.data?.error || e?.friendlyMessage || e?.message || String(e)
      setError('加载失败：' + detail)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    if (!isAdmin) return
    loadUsers(searchKeyword)
  }, [isAdmin, searchKeyword, loadUsers])

  if (!isAdmin) return <Navigate to="/" replace />

  const handleSearch = (e) => {
    e.preventDefault()
    setSearchKeyword(searchInput.trim())
  }

  const handleConfirm = async () => {
    if (!confirmAction) return
    const { type, user, newRole } = confirmAction
    setConfirmAction(null)
    try {
      if (type === 'role') {
        await updateUserRole(user.id, newRole)
        setUsers(prev => prev.map(u => u.id === user.id ? { ...u, role: newRole } : u))
      } else if (type === 'delete') {
        await deleteUser(user.id)
        setUsers(prev => prev.filter(u => u.id !== user.id))
      }
    } catch (e) {
      const detail = e?.response?.data?.message || e?.friendlyMessage || e?.message || String(e)
      alert('操作失败：' + detail)
    }
  }

  return (
    <div className="flex-1 overflow-auto p-8 max-w-6xl mx-auto w-full">
      {/* 标题栏 */}
      <div className="flex items-center justify-between mb-4">
        <div>
          <h1 className="text-[18px] font-semibold text-gray-900">用户管理</h1>
          <div className="text-[12px] text-gray-500 mt-1">管理系统内注册用户，支持角色分配与账号删除</div>
        </div>
        <button
          onClick={() => loadUsers(searchKeyword)}
          className="px-3 py-1.5 text-[13px] rounded-md text-white bg-brand-600 hover:bg-brand-700"
        >刷新</button>
      </div>

      {/* 搜索区 */}
      <div className="bg-white border border-gray-200 rounded-xl p-4 mb-4 flex items-end gap-3 flex-wrap">
        <form onSubmit={handleSearch} className="flex items-end gap-2">
          <div>
            <label className="block text-[12px] text-gray-500 mb-1">搜索用户</label>
            <input
              value={searchInput}
              onChange={e => setSearchInput(e.target.value)}
              placeholder="按邮箱 / 手机号 / 名称搜索"
              className="px-3 py-1.5 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400 min-w-[280px]"
            />
          </div>
          <button
            type="submit"
            className="px-3 py-1.5 text-[13px] rounded-md text-gray-700 border border-gray-200 hover:bg-gray-50"
          >搜索</button>
          <button
            type="button"
            onClick={() => { setSearchInput(''); setSearchKeyword('') }}
            className="px-3 py-1.5 text-[13px] rounded-md text-gray-500 hover:text-gray-700"
          >重置</button>
        </form>
        <div className="ml-auto text-[12px] text-gray-400">共 {users.length} 位用户</div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="mb-3 text-[12px] text-rose-600 bg-rose-50 border border-rose-200 rounded-md px-3 py-2">
          {error}
        </div>
      )}

      {/* 用户表格 */}
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <table className="w-full text-[13px]">
          <thead className="bg-gray-50 text-gray-500 text-[12px]">
            <tr>
              <th className="text-left px-3 py-2 font-normal">用户名</th>
              <th className="text-left px-3 py-2 font-normal">邮箱</th>
              <th className="text-left px-3 py-2 font-normal">手机号</th>
              <th className="text-left px-3 py-2 font-normal w-[100px]">角色</th>
              <th className="text-left px-3 py-2 font-normal w-[140px]">注册时间</th>
              <th className="text-left px-3 py-2 font-normal w-[140px]">最后登录</th>
              <th className="text-left px-3 py-2 font-normal w-[120px]">操作</th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr><td colSpan={7} className="px-3 py-8 text-center text-gray-400">加载中…</td></tr>
            )}
            {!loading && users.length === 0 && (
              <tr><td colSpan={7} className="px-3 py-8 text-center text-gray-400">暂无用户数据</td></tr>
            )}
            {!loading && users.map(u => {
              const isSuperAdmin = u.email === SUPER_ADMIN_EMAIL
              const isAdmin = u.role === 'admin'
              return (
                <tr key={u.id} className="border-t border-gray-100 hover:bg-gray-50/60">
                  <td className="px-3 py-2 text-gray-800 font-medium">{u.name || '—'}</td>
                  <td className="px-3 py-2 text-gray-700">{u.email || '—'}</td>
                  <td className="px-3 py-2 text-gray-700">{u.phone || '—'}</td>
                  <td className="px-3 py-2">
                    {isAdmin ? (
                      <span className="inline-block px-1.5 py-0.5 rounded text-[11px] bg-purple-100 text-purple-700">管理员</span>
                    ) : (
                      <span className="inline-block px-1.5 py-0.5 rounded text-[11px] bg-gray-100 text-gray-600">普通用户</span>
                    )}
                  </td>
                  <td className="px-3 py-2 text-gray-600 whitespace-nowrap">{fmtTime(u.created_at)}</td>
                  <td className="px-3 py-2 text-gray-600 whitespace-nowrap">{fmtTime(u.last_login_at)}</td>
                  <td className="px-3 py-2">
                    {isSuperAdmin ? (
                      <span className="text-[11px] text-gray-400">超级管理员</span>
                    ) : (
                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => setConfirmAction({
                            type: 'role',
                            user: u,
                            newRole: isAdmin ? 'user' : 'admin'
                          })}
                          className="px-2 py-1 text-[12px] rounded border border-gray-200 text-gray-600 hover:bg-gray-50 hover:text-brand-600 transition"
                        >
                          {isAdmin ? '取消管理员' : '设为管理员'}
                        </button>
                        <button
                          onClick={() => setConfirmAction({ type: 'delete', user: u })}
                          className="px-2 py-1 text-[12px] rounded border border-gray-200 text-gray-600 hover:bg-rose-50 hover:text-rose-600 hover:border-rose-200 transition"
                        >
                          删除
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>

      {/* 确认弹窗 */}
      {confirmAction && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={() => setConfirmAction(null)}>
          <div
            className="bg-white rounded-xl shadow-2xl w-[400px] max-w-[92vw] p-6"
            onClick={e => e.stopPropagation()}
          >
            <h3 className="text-[16px] font-semibold text-gray-900 mb-2">
              {confirmAction.type === 'role' ? '确认修改角色' : '确认删除用户'}
            </h3>
            <p className="text-[13px] text-gray-600 mb-5">
              {confirmAction.type === 'role'
                ? `确定将用户「${confirmAction.user.name || confirmAction.user.email}」的角色${confirmAction.newRole === 'admin' ? '升级为管理员' : '降级为普通用户'}吗？`
                : `确定删除用户「${confirmAction.user.name || confirmAction.user.email}」吗？此操作不可撤销。`
              }
            </p>
            <div className="flex items-center justify-end gap-2">
              <button
                onClick={() => setConfirmAction(null)}
                className="px-3.5 py-1.5 text-[13px] rounded-md text-gray-600 bg-white border border-gray-200 hover:bg-gray-50"
              >取消</button>
              <button
                onClick={handleConfirm}
                className={[
                  'px-3.5 py-1.5 text-[13px] rounded-md text-white',
                  confirmAction.type === 'delete'
                    ? 'bg-rose-600 hover:bg-rose-700'
                    : 'bg-brand-600 hover:bg-brand-700'
                ].join(' ')}
              >确认</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
