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

import { useState, useEffect } from 'react'
import { Modal, Transfer, message, type TransferProps } from 'antd'
import { getErrorMessage } from '@/lib/errors'
import type { User, Role } from '@/types'
import { assignUserRoles } from '@/services/users'

interface AssignRolesModalProps {
  open: boolean
  user: User | null
  currentRoles: Role[]
  allRoles: Role[]
  onSuccess: () => void
  onClose: () => void
}

export function AssignRolesModal({
  open,
  user,
  currentRoles,
  allRoles,
  onSuccess,
  onClose,
}: AssignRolesModalProps) {
  const [loading, setLoading] = useState(false)
  const [targetKeys, setTargetKeys] = useState<string[]>(
    currentRoles.map((r) => String(r.id))
  )

  // 弹窗打开时显示 loading，关闭时重置
  useEffect(() => {
    if (open) {
      setTargetKeys(currentRoles.map((r) => String(r.id)))
    }
  }, [open, currentRoles])

  // 当 currentRoles 变化时更新 targetKeys
  useEffect(() => {
    setTargetKeys(currentRoles.map((r) => String(r.id)))
  }, [currentRoles])

  const handleChange: TransferProps['onChange'] = (newTargetKeys) => {
    setTargetKeys(newTargetKeys as string[])
  }

  const handleSubmit = async () => {
    if (!user) return

    setLoading(true)
    try {
      await assignUserRoles(user.id, {
        role_ids: targetKeys.map(Number),
      })
      message.success('角色分配成功')
      onSuccess()
    } catch (err) {
      message.error(getErrorMessage(err, '角色分配失败'))
    } finally {
      setLoading(false)
    }
  }

  const handleCancel = () => {
    setTargetKeys(currentRoles.map((r) => String(r.id)))
    onClose()
  }

  // Transfer 数据源
  const dataSource = allRoles.map((role) => ({
    key: String(role.id),
    title: role.name,
    description: role.description || '',
    disabled: role.is_system, // 系统角色不可取消
  }))

  return (
    <Modal
      title={`分配角色 - ${user?.username || ''}`}
      open={open}
      onOk={handleSubmit}
      onCancel={handleCancel}
      confirmLoading={loading}
      width={640}
      destroyOnHidden
    >
      <p style={{ marginBottom: 16, color: 'var(--color-text-muted)' }}>
        选择要分配给该用户的角色。系统角色不可取消。
      </p>
      <Transfer
        dataSource={dataSource}
        titles={['可分配角色', '已分配角色']}
        targetKeys={targetKeys}
        onChange={handleChange}
        render={(item) => item.title}
        listStyle={{ width: 256, height: 320 }}
        showSearch
        filterOption={(input, item) =>
          item.title.toLowerCase().includes(input.toLowerCase()) ||
          item.description.toLowerCase().includes(input.toLowerCase())
        }
      />
    </Modal>
  )
}
