/**
 * 权限创建/编辑弹窗
 */

import { useState, useEffect } from 'react'
import {
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  message,
} from 'antd'
import { getErrorMessage, isFormValidationError } from '@/lib/errors'
import type { Permission, PermissionType } from '@/types/permission'
import { PermissionTypeText } from '@/types/permission'
import { createPermission, updatePermission } from '@/services/permissions'

interface PermissionFormModalProps {
  open: boolean
  permission: Permission | null
  parentPermission: Permission | null
  permissions: Permission[]
  onSuccess: () => void
  onClose: () => void
}

export function PermissionFormModal({
  open,
  permission,
  parentPermission,
  permissions,
  onSuccess,
  onClose,
}: PermissionFormModalProps) {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const isEdit = !!permission

  // 初始化表单
  useEffect(() => {
    if (open) {
      if (permission) {
        form.setFieldsValue({
          name: permission.name,
          code: permission.code,
          type: permission.type,
          parent_id: permission.parent_id,
          path: permission.path,
          icon: permission.icon,
          sort: permission.sort,
        })
      } else {
        form.resetFields()
        // 如果有父权限，设置 parent_id
        if (parentPermission) {
          form.setFieldsValue({
            parent_id: parentPermission.id,
          })
        }
      }
    }
  }, [open, permission, parentPermission, form])

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

      if (isEdit && permission) {
        await updatePermission(permission.id, {
          name: values.name,
          path: values.path,
          icon: values.icon,
          sort: values.sort,
        })
        message.success('权限已更新')
      } else {
        await createPermission({
          name: values.name,
          code: values.code,
          type: values.type,
          parent_id: values.parent_id || null,
          path: values.path,
          icon: values.icon,
          sort: values.sort || 0,
        })
        message.success('权限已创建')
      }

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

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

  // 构建父权限选项（树形结构）
  const buildParentOptions = (perms: Permission[], level = 0): Array<{ value: number; label: string }> => {
    const options: Array<{ value: number; label: string }> = []
    perms.forEach((perm) => {
      // 排除当前权限及其子权限（编辑时不能选择自己或子权限作为父级）
      if (isEdit && permission && perm.id === permission.id) {
        return
      }
      options.push({
        value: perm.id,
        label: `${'　'.repeat(level)}${perm.name}`,
      })
      if (perm.children && perm.children.length > 0) {
        options.push(...buildParentOptions(perm.children, level + 1))
      }
    })
    return options
  }

  return (
    <Modal
      title={isEdit ? '编辑权限' : parentPermission ? `创建子权限 - ${parentPermission.name}` : '创建权限'}
      open={open}
      onOk={handleSubmit}
      onCancel={handleClose}
      confirmLoading={loading}
      width={520}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: 'menu' as PermissionType,
          sort: 0,
        }}
      >
        <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: 100, message: '权限代码不能超过100个字符' },
          ]}
          extra="权限代码用于权限判断，创建后不可修改"
        >
          <Input placeholder="如：user:manage" disabled={isEdit} />
        </Form.Item>

        <Form.Item
          name="type"
          label="权限类型"
          rules={[{ required: true, message: '请选择权限类型' }]}
          extra="创建后不可修改"
        >
          <Select disabled={isEdit}>
            {Object.entries(PermissionTypeText).map(([value, label]) => (
              <Select.Option key={value} value={value}>
                {label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="parent_id"
          label="父级权限"
          extra="不选择则为顶级权限"
        >
          <Select
            placeholder="选择父级权限"
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={buildParentOptions(permissions)}
            disabled={isEdit}
          />
        </Form.Item>

        <Form.Item
          name="path"
          label="路由路径"
          extra="菜单类型权限需要填写路由路径"
        >
          <Input placeholder="如：/admin/users" />
        </Form.Item>

        <Form.Item
          name="icon"
          label="图标"
          extra="菜单类型权限可填写图标名称"
        >
          <Input placeholder="如：UserOutlined" />
        </Form.Item>

        <Form.Item
          name="sort"
          label="排序"
          extra="数值越小越靠前"
        >
          <InputNumber min={0} max={999} style={{ width: '100%' }} />
        </Form.Item>
      </Form>
    </Modal>
  )
}
