/**
 * 角色创建/编辑弹窗
 */

import { useState, useEffect } from 'react'
import {
  Modal,
  Form,
  Input,
  Switch,
  message,
} from 'antd'
import { getErrorMessage, isFormValidationError } from '@/lib/errors'
import type { Role } from '@/types/role'
import { createRole, updateRole } from '@/services/roles'

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

export function RoleFormModal({ open, role, onSuccess, onClose }: RoleFormModalProps) {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const isEdit = !!role

  // 初始化表单
  useEffect(() => {
    if (open) {
      if (role) {
        form.setFieldsValue({
          name: role.name,
          code: role.code,
          description: role.description,
          is_default: role.is_default,
        })
      } else {
        form.resetFields()
      }
    }
  }, [open, role, form])

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)

      if (isEdit && role) {
        await updateRole(role.id, {
          name: values.name,
          description: values.description,
          is_default: values.is_default,
        })
        message.success('角色已更新')
      } else {
        await createRole(values)
        message.success('角色已创建')
      }

      onSuccess()
    } catch (err) {
      if (isFormValidationError(err)) {
        return
      }
      message.error(getErrorMessage(err, '操作失败'))
    } finally {
      setLoading(false)
    }
  }

  // 关闭时重置
  const handleClose = () => {
    form.resetFields()
    onClose()
  }

  return (
    <Modal
      title={isEdit ? '编辑角色' : '创建角色'}
      open={open}
      onOk={handleSubmit}
      onCancel={handleClose}
      confirmLoading={loading}
      width={520}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          is_default: false,
        }}
      >
        <Form.Item
          name="name"
          label="角色名称"
          rules={[
            { required: true, message: '请输入角色名称' },
            { max: 50, message: '角色名称不能超过50个字符' },
          ]}
        >
          <Input placeholder="如：内容管理员" />
        </Form.Item>

        <Form.Item
          name="code"
          label="角色代码"
          rules={[
            { required: true, message: '请输入角色代码' },
            { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '角色代码必须以字母开头，只能包含字母、数字和下划线' },
            { max: 50, message: '角色代码不能超过50个字符' },
          ]}
          extra="角色代码用于权限判断，创建后不可修改"
        >
          <Input placeholder="如：content_manager" disabled={isEdit} />
        </Form.Item>

        <Form.Item
          name="description"
          label="角色描述"
          rules={[
            { max: 200, message: '角色描述不能超过200个字符' },
          ]}
        >
          <Input.TextArea rows={3} placeholder="描述该角色的职责和权限范围" />
        </Form.Item>

        <Form.Item
          name="is_default"
          label="默认角色"
          valuePropName="checked"
          extra="默认角色会在新用户注册时自动分配"
        >
          <Switch checkedChildren="是" unCheckedChildren="否" />
        </Form.Item>
      </Form>
    </Modal>
  )
}
