import { useEffect, useState } from 'react'
import { Alert, Button, Checkbox, Form, Input, Modal, Select, Space, message } from 'antd'

import { getErrorMessage, isFormValidationError } from '@/lib/errors'
import { createUser } from '@/services/users'
import type { CreateUserRequest, CreatableUserStatus, Role } from '@/types'

interface CreateUserModalProps {
  open: boolean
  roles: Role[]
  onSuccess: () => void
  onClose: () => void
}

type CreateUserFormValues = CreateUserRequest

const STATUS_OPTIONS: Array<{ value: CreatableUserStatus; label: string }> = [
  { value: 1, label: '已激活' },
  { value: 0, label: '未激活' },
  { value: 3, label: '已禁用' },
]

export function CreateUserModal({ open, roles, onSuccess, onClose }: CreateUserModalProps) {
  const [form] = Form.useForm<CreateUserFormValues>()
  const [loading, setLoading] = useState(false)
  const email = Form.useWatch('email', form)
  const sendActivationEmail = Form.useWatch('send_activation_email', form) ?? false

  useEffect(() => {
    if (open) {
      form.setFieldsValue({
        status: 1,
        role_ids: [],
        send_activation_email: false,
      })
      return
    }

    form.resetFields()
  }, [open, form])

  useEffect(() => {
    if (!email && sendActivationEmail) {
      form.setFieldValue('send_activation_email', false)
    }
  }, [email, form, sendActivationEmail])

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)

      await createUser({
        username: values.username.trim(),
        password: values.password,
        email: values.email?.trim() || undefined,
        phone: values.phone?.trim() || undefined,
        nickname: values.nickname?.trim() || undefined,
        role_ids: values.role_ids?.length ? values.role_ids : undefined,
        status: values.send_activation_email ? 0 : values.status,
        send_activation_email: Boolean(values.send_activation_email),
      })

      message.success(values.send_activation_email ? '用户已创建，激活邮件已发送' : '用户已创建')
      onSuccess()
    } catch (error) {
      if (isFormValidationError(error)) {
        return
      }
      message.error(getErrorMessage(error, '创建用户失败'))
    } finally {
      setLoading(false)
    }
  }

  const handleClose = () => {
    form.resetFields()
    onClose()
  }

  return (
    <Modal
      title="创建用户"
      open={open}
      onCancel={handleClose}
      destroyOnHidden
      footer={
        <Space>
          <Button onClick={handleClose}>取消</Button>
          <Button type="primary" loading={loading} onClick={() => void handleSubmit()}>
            创建用户
          </Button>
        </Space>
      }
    >
      <Alert
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
        message="未选择初始角色时，系统会自动分配默认角色。"
      />

      <Form<CreateUserFormValues> form={form} layout="vertical">
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input placeholder="请输入用户名" autoComplete="off" />
        </Form.Item>

        <Form.Item
          name="password"
          label="初始密码"
          rules={[{ required: true, message: '请输入初始密码' }]}
        >
          <Input.Password placeholder="请输入初始密码" autoComplete="new-password" />
        </Form.Item>

        <Form.Item
          name="email"
          label="邮箱"
          rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}
        >
          <Input placeholder="邮箱地址" autoComplete="off" />
        </Form.Item>

        <Form.Item
          name="phone"
          label="手机号"
          rules={[{ pattern: /^1\d{10}$/, message: '请输入有效的手机号' }]}
        >
          <Input placeholder="手机号" autoComplete="off" />
        </Form.Item>

        <Form.Item name="nickname" label="昵称">
          <Input placeholder="昵称，不填则默认使用用户名" autoComplete="off" />
        </Form.Item>

        <Form.Item
          name="status"
          label="初始状态"
          extra={sendActivationEmail ? '发送激活邮件时，用户状态会自动设置为未激活。' : undefined}
        >
          <Select
            options={STATUS_OPTIONS}
            disabled={sendActivationEmail}
            placeholder="请选择初始状态"
          />
        </Form.Item>

        <Form.Item
          name="role_ids"
          label="初始角色"
          extra="可多选；留空时自动分配默认角色。"
        >
          <Select
            mode="multiple"
            allowClear
            placeholder="请选择初始角色"
            options={roles.map((role) => ({
              value: role.id,
              label: role.name,
            }))}
          />
        </Form.Item>

        <Form.Item name="send_activation_email" valuePropName="checked">
          <Checkbox disabled={!email}>创建后发送激活邮件</Checkbox>
        </Form.Item>
      </Form>
    </Modal>
  )
}
