/**
 * 用户管理页
 *
 * 功能：
 * - 用户创建、列表、筛选、详情、编辑、状态切换、删除、角色分配
 * - 批量操作：批量启用、批量禁用、批量删除
 */

import { useState, useEffect, useCallback } from 'react'
import {
  Table,
  Button,
  Space,
  Tag,
  Input,
  Select,
  DatePicker,
  Popconfirm,
  message,
  type TableColumnsType,
  type TablePaginationConfig,
} from 'antd'
import type { Key } from 'antd/es/table/interface'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  TeamOutlined,
} from '@ant-design/icons'
import dayjs from 'dayjs'
import { PageHeader } from '@/components/common'
import { PageEmpty, PageError } from '@/components/feedback'
import { PageLayout, FilterCard, TableCard } from '@/components/layout'
import { getErrorMessage } from '@/lib/errors'
import { useAuth } from '@/app/providers/auth-context'
import {
  listUsers,
  deleteUser,
  updateUserStatus,
  getUserRoles,
  batchUpdateStatus,
  batchDelete,
} from '@/services/users'
import { listRoles } from '@/services/roles'
import type { User, UserListParams, UserStatus } from '@/types/user'
import type { Role } from '@/types/auth'
import { UserStatusText, UserStatusColor } from '@/types/user'
import { UserDetailDrawer } from './UserDetailDrawer'
import { UserEditDrawer } from './UserEditDrawer'
import { AssignRolesModal } from './AssignRolesModal'
import { CreateUserModal } from './CreateUserModal'

const { RangePicker } = DatePicker

export function UsersPage() {
  // 当前登录用户（用于防止删除自己）
  const { user: currentUser } = useAuth()

  // 列表数据
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [users, setUsers] = useState<User[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)

  // 筛选条件
  const [keyword, setKeyword] = useState('')
  const [statusFilter, setStatusFilter] = useState<UserStatus | undefined>()
  const [createdFrom, setCreatedFrom] = useState<string | undefined>()
  const [createdTo, setCreatedTo] = useState<string | undefined>()
  const [sortBy, setSortBy] = useState<string | undefined>()
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc' | undefined>()

  // 角色列表（用于筛选和分配）
  const [roles, setRoles] = useState<Role[]>([])
  const [roleFilter, setRoleFilter] = useState<number | undefined>()

  // 抽屉/弹窗
  const [detailVisible, setDetailVisible] = useState(false)
  const [createVisible, setCreateVisible] = useState(false)
  const [editVisible, setEditVisible] = useState(false)
  const [assignRolesVisible, setAssignRolesVisible] = useState(false)
  const [selectedUser, setSelectedUser] = useState<User | null>(null)
  const [selectedUserRoles, setSelectedUserRoles] = useState<Role[]>([])

  // 批量选择
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])

  // 加载角色列表
  useEffect(() => {
    const fetchRoles = async () => {
      try {
        const roleList = await listRoles({ page: 1, page_size: 100 })
        setRoles(roleList.items)
      } catch {
        // 获取角色列表失败，忽略
      }
    }
    fetchRoles()
  }, [])

  // 筛选条件变化时重置到第一页
  useEffect(() => {
    setPage(1)
  }, [keyword, statusFilter, roleFilter, createdFrom, createdTo, sortBy, sortOrder])

  // 加载用户列表
  const fetchUsers = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params: UserListParams = {
        page,
        page_size: pageSize,
        keyword: keyword || undefined,
        status: statusFilter,
        role_ids: roleFilter ? String(roleFilter) : undefined,
        created_from: createdFrom,
        created_to: createdTo,
        sort_by: sortBy,
        sort_order: sortOrder,
      }
      const result = await listUsers(params)
      setUsers(result.items)
      setTotal(result.total)
    } catch (err) {
      setError(getErrorMessage(err, '获取用户列表失败'))
    } finally {
      setLoading(false)
    }
  }, [page, pageSize, keyword, statusFilter, roleFilter, createdFrom, createdTo, sortBy, sortOrder])

  useEffect(() => {
    fetchUsers()
  }, [fetchUsers])

  // 重置筛选
  const handleReset = () => {
    setKeyword('')
    setStatusFilter(undefined)
    setRoleFilter(undefined)
    setCreatedFrom(undefined)
    setCreatedTo(undefined)
    setSortBy(undefined)
    setSortOrder(undefined)
    setPage(1)
  }

  // 查看详情
  const handleViewDetail = async (user: User) => {
    setSelectedUser(user)
    setDetailVisible(true)
  }

  // 编辑用户
  const handleEdit = async (user: User) => {
    setSelectedUser(user)
    setEditVisible(true)
  }

  // 删除用户
  const handleDelete = async (user: User) => {
    // 防止删除自己
    if (currentUser && user.id === currentUser.id) {
      message.error('不能删除当前登录的账号')
      return
    }
    try {
      await deleteUser(user.id)
      message.success(`用户 ${user.username} 已删除`)
      fetchUsers()
    } catch (err) {
      message.error(getErrorMessage(err, '删除失败'))
    }
  }

  // 切换状态
  const handleToggleStatus = async (user: User) => {
    // 状态转换逻辑：
    // - 1（已激活）-> 3（禁用）
    // - 0（未激活）-> 1（激活）
    // - 2（已锁定）-> 1（解锁并激活）
    // - 3（已禁用）-> 1（激活）
    const newStatus: UserStatus = user.status === 1 ? 3 : 1
    try {
      await updateUserStatus(user.id, { status: newStatus })
      message.success('状态已更新')
      fetchUsers()
    } catch (err) {
      message.error(getErrorMessage(err, '状态更新失败'))
    }
  }

  // 分配角色
  const handleAssignRoles = async (user: User) => {
    setSelectedUser(user)
    try {
      const userRoles = await getUserRoles(user.id)
      setSelectedUserRoles(userRoles)
      setAssignRolesVisible(true)
    } catch (err) {
      message.error(getErrorMessage(err, '获取用户角色失败'))
    }
  }

  // 编辑成功回调
  const handleEditSuccess = () => {
    setEditVisible(false)
    fetchUsers()
  }

  const handleCreateSuccess = () => {
    setCreateVisible(false)
    fetchUsers()
  }

  // 角色分配成功回调
  const handleAssignRolesSuccess = () => {
    setAssignRolesVisible(false)
    fetchUsers()
  }

  // 批量启用
  const handleBatchEnable = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择用户')
      return
    }
    try {
      const ids = selectedRowKeys.map(Number)
      await batchUpdateStatus(ids, 1)
      message.success(`已启用 ${ids.length} 个用户`)
      setSelectedRowKeys([])
      fetchUsers()
    } catch (err) {
      message.error(getErrorMessage(err, '批量启用失败'))
    }
  }

  // 批量禁用
  const handleBatchDisable = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择用户')
      return
    }
    try {
      const ids = selectedRowKeys.map(Number)
      await batchUpdateStatus(ids, 3)
      message.success(`已禁用 ${ids.length} 个用户`)
      setSelectedRowKeys([])
      fetchUsers()
    } catch (err) {
      message.error(getErrorMessage(err, '批量禁用失败'))
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择用户')
      return
    }
    // 防止删除自己
    if (currentUser && selectedRowKeys.includes(currentUser.id)) {
      message.error('不能删除当前登录的账号')
      return
    }
    try {
      const ids = selectedRowKeys.map(Number)
      await batchDelete(ids)
      message.success(`已删除 ${ids.length} 个用户`)
      setSelectedRowKeys([])
      fetchUsers()
    } catch (err) {
      message.error(getErrorMessage(err, '批量删除失败'))
    }
  }

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: Key[]) => setSelectedRowKeys(keys),
  }

  // 表格列定义
  const columns: TableColumnsType<User> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
      fixed: 'left',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      width: 100,
      render: (text) => text || '-',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      render: (text) => text || '-',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 130,
      render: (text) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: UserStatus) => (
        <Tag color={UserStatusColor[status]}>{UserStatusText[status]}</Tag>
      ),
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_at',
      key: 'last_login_at',
      width: 160,
      render: (text) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-'),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<TeamOutlined />}
            onClick={() => handleAssignRoles(record)}
          >
            角色
          </Button>
          {record.status === 1 ? (
            <Popconfirm
              title="确定要禁用该用户吗？"
              onConfirm={() => handleToggleStatus(record)}
            >
              <Button type="link" size="small" danger>
                禁用
              </Button>
            </Popconfirm>
          ) : record.status === 3 ? (
            <Popconfirm
              title="确定要激活该用户吗？"
              onConfirm={() => handleToggleStatus(record)}
            >
              <Button type="link" size="small">
                激活
              </Button>
            </Popconfirm>
          ) : record.status === 2 ? (
            <Popconfirm
              title="该用户因多次失败已被锁定，确定要解锁并激活吗？"
              onConfirm={() => handleToggleStatus(record)}
            >
              <Button type="link" size="small">
                解锁
              </Button>
            </Popconfirm>
          ) : record.status === 0 ? (
            <Popconfirm
              title="该用户尚未激活，确定要激活该用户吗？"
              onConfirm={() => handleToggleStatus(record)}
            >
              <Button type="link" size="small">
                激活
              </Button>
            </Popconfirm>
          ) : null}
          <Popconfirm
            title={`确定要删除用户「${record.username}」吗？此操作不可恢复。`}
            onConfirm={() => handleDelete(record)}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  // 分页配置
  const paginationConfig: TablePaginationConfig = {
    current: page,
    pageSize,
    total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
    onChange: (p, ps) => {
      setPage(p)
      setPageSize(ps)
    },
  }

  if (error) {
    return <PageError description={error} onRetry={fetchUsers} />
  }

  return (
    <PageLayout>
      <PageHeader
        title="用户管理"
        description="管理系统用户，支持创建、查看、编辑、状态管理和角色分配"
        actions={
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateVisible(true)}>
              创建用户
            </Button>
            <Button icon={<ReloadOutlined />} onClick={fetchUsers}>
              刷新
            </Button>
          </Space>
        }
      />

      {/* 批量操作工具栏 */}
      {selectedRowKeys.length > 0 && (
        <div style={{ marginBottom: 16, padding: '8px 16px', background: '#f0f5ff', borderRadius: 4 }}>
          <Space>
            <span>已选择 {selectedRowKeys.length} 个用户：</span>
            <Button size="small" onClick={handleBatchEnable}>批量启用</Button>
            <Button size="small" onClick={handleBatchDisable}>批量禁用</Button>
            <Popconfirm
              title={`确定要删除选中的 ${selectedRowKeys.length} 个用户吗？此操作不可恢复。`}
              onConfirm={handleBatchDelete}
            >
              <Button size="small" danger>批量删除</Button>
            </Popconfirm>
            <Button size="small" type="link" onClick={() => setSelectedRowKeys([])}>
              取消选择
            </Button>
          </Space>
        </div>
      )}

      {/* 筛选区域 */}
      <FilterCard>
        <Space wrap size="middle">
          <Input
            placeholder="用户名/邮箱/手机号"
            prefix={<SearchOutlined />}
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onPressEnter={() => void fetchUsers()}
            style={{ width: 200 }}
            allowClear
          />
          <Select
            placeholder="用户状态"
            value={statusFilter}
            onChange={setStatusFilter}
            allowClear
            style={{ width: 120 }}
            options={[
              { value: 0, label: '未激活' },
              { value: 1, label: '已激活' },
              { value: 2, label: '已锁定' },
              { value: 3, label: '已禁用' },
            ]}
          />
          <Select
            placeholder="按角色筛选"
            value={roleFilter}
            onChange={setRoleFilter}
            allowClear
            style={{ width: 150 }}
            options={roles.map((r) => ({ value: r.id, label: r.name }))}
          />
          <RangePicker
            placeholder={['创建开始', '创建结束']}
            onChange={(_, dateStrings) => {
              setCreatedFrom(dateStrings[0] || undefined)
              setCreatedTo(dateStrings[1] || undefined)
            }}
          />
          <Select
            placeholder="排序字段"
            value={sortBy}
            onChange={setSortBy}
            allowClear
            style={{ width: 120 }}
            options={[
              { value: 'created_at', label: '创建时间' },
              { value: 'last_login_at', label: '最后登录' },
              { value: 'username', label: '用户名' },
            ]}
          />
          <Select
            placeholder="排序方向"
            value={sortOrder}
            onChange={setSortOrder}
            allowClear
            style={{ width: 100 }}
            options={[
              { value: 'asc', label: '升序' },
              { value: 'desc', label: '降序' },
            ]}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={fetchUsers}>
            查询
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </Space>
      </FilterCard>

      {/* 用户列表 */}
      <TableCard>
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          scroll={{ x: 1200 }}
          rowSelection={rowSelection}
          locale={{
            emptyText: (
              <PageEmpty
                description="暂无用户数据"
              />
            ),
          }}
        />
      </TableCard>

      {/* 详情抽屉 */}
      <UserDetailDrawer
        open={detailVisible}
        userId={selectedUser?.id}
        onClose={() => setDetailVisible(false)}
      />

      {/* 编辑抽屉 */}
      <UserEditDrawer
        open={editVisible}
        user={selectedUser}
        onSuccess={handleEditSuccess}
        onClose={() => setEditVisible(false)}
      />

      {/* 创建用户弹窗 */}
      <CreateUserModal
        open={createVisible}
        roles={roles}
        onSuccess={handleCreateSuccess}
        onClose={() => setCreateVisible(false)}
      />

      {/* 角色分配弹窗 */}
      <AssignRolesModal
        open={assignRolesVisible}
        user={selectedUser}
        currentRoles={selectedUserRoles}
        allRoles={roles}
        onSuccess={handleAssignRolesSuccess}
        onClose={() => setAssignRolesVisible(false)}
      />
    </PageLayout>
  )
}
