import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi, beforeEach } from 'vitest'

import type { Role } from '@/types'
import { CreateUserModal } from './CreateUserModal'

const createUserMock = vi.fn()
const originalGetComputedStyle = window.getComputedStyle

vi.mock('@/services/users', () => ({
  createUser: (payload: unknown) => createUserMock(payload),
}))

const roles: Role[] = [
  {
    id: 1,
    name: '用户',
    code: 'user',
    description: 'default user role',
    is_system: true,
    is_default: true,
    status: 1,
  },
]

describe('CreateUserModal', () => {
  beforeEach(() => {
    createUserMock.mockReset()
    createUserMock.mockResolvedValue(undefined)
    vi.spyOn(window, 'getComputedStyle').mockImplementation((element) => {
      return originalGetComputedStyle.call(window, element)
    })
  })

  it('submits the create-user payload and enables activation email when selected', async () => {
    const user = userEvent.setup()
    const onSuccess = vi.fn()

    render(
      <CreateUserModal
        open
        roles={roles}
        onSuccess={onSuccess}
        onClose={vi.fn()}
      />,
    )

    await user.type(screen.getByPlaceholderText('请输入用户名'), 'created-user')
    await user.type(screen.getByPlaceholderText('请输入初始密码'), 'Pass123!@#')
    await user.type(screen.getByPlaceholderText('邮箱地址'), 'created-user@example.com')
    await user.click(screen.getByRole('checkbox', { name: '创建后发送激活邮件' }))
    await user.click(screen.getByRole('button', { name: '创建用户' }))

    await waitFor(() =>
      expect(createUserMock).toHaveBeenCalledWith({
        username: 'created-user',
        password: 'Pass123!@#',
        email: 'created-user@example.com',
        phone: undefined,
        nickname: undefined,
        role_ids: undefined,
        status: 0,
        send_activation_email: true,
      }),
    )
    expect(onSuccess).toHaveBeenCalledTimes(1)
  })
})
