/**
 * 角色权限分配弹窗
 */

import { useState, useEffect } from 'react'
import { Modal, Tree, Spin, message, Empty } from 'antd'
import type { TreeProps } from 'antd'
import { getErrorMessage } from '@/lib/errors'
import type { Role } from '@/types/role'
import type { Permission } from '@/types/permission'
import { getRolePermissions, assignRolePermissions } from '@/services/roles'
import { getPermissionTree } from '@/services/permissions'

interface RolePermissionsModalProps {
  open: boolean
  role: Role | null
  onSuccess: () => void
  onClose: () => void
}

export function RolePermissionsModal({
  open,
  role,
  onSuccess,
  onClose,
}: RolePermissionsModalProps) {
  const [loading, setLoading] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [permissions, setPermissions] = useState<Permission[]>([])
  const [checkedKeys, setCheckedKeys] = useState<string[]>([])

  // 加载权限树和角色权限
  useEffect(() => {
    if (open && role) {
      const fetchData = async () => {
        setLoading(true)
        try {
          const [permTree, rolePerms] = await Promise.all([
            getPermissionTree(),
            getRolePermissions(role.id),
          ])
          setPermissions(permTree)
          setCheckedKeys(rolePerms.map(String))
        } catch (err) {
          message.error(getErrorMessage(err, '加载权限数据失败'))
        } finally {
          setLoading(false)
        }
      }
      fetchData()
    }
  }, [open, role])

  // 处理勾选
  const handleCheck: TreeProps['onCheck'] = (keys) => {
    setCheckedKeys(keys as string[])
  }

  // 提交权限分配
  const handleSubmit = async () => {
    if (!role) return

    setSubmitting(true)
    try {
      await assignRolePermissions(role.id, checkedKeys.map(Number))
      message.success('权限分配成功')
      onSuccess()
    } catch (err) {
      message.error(getErrorMessage(err, '权限分配失败'))
    } finally {
      setSubmitting(false)
    }
  }

  // 将权限树转换为 Tree 组件数据
  const buildTreeData = (perms: Permission[]): TreeProps['treeData'] => {
    return perms.map((perm) => ({
      key: String(perm.id),
      title: perm.name,
      children: perm.children ? buildTreeData(perm.children) : undefined,
    }))
  }

  return (
    <Modal
      title={`分配权限 - ${role?.name || ''}`}
      open={open}
      onOk={handleSubmit}
      onCancel={onClose}
      confirmLoading={submitting}
      width={600}
    >
      <p style={{ marginBottom: 16, color: 'var(--color-text-muted)' }}>
        选择要分配给该角色的权限。
      </p>
      <Spin spinning={loading}>
        {permissions.length > 0 ? (
          <Tree
            checkable
            checkedKeys={checkedKeys}
            onCheck={handleCheck}
            treeData={buildTreeData(permissions)}
            style={{ minHeight: 200, maxHeight: 400, overflow: 'auto' }}
            defaultExpandAll
          />
        ) : (
          <Empty description="暂无权限数据" />
        )}
      </Spin>
    </Modal>
  )
}
