<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'

import { createAdminMgrUser, updateAdminMgrUser, type AdminMgrUser, type CreateAdminRequest, type UpdateAdminRequest } from '@/features/admin/api/adminMgr'

const props = defineProps<{
  modelValue: boolean
  admin?: AdminMgrUser | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
  (e: 'saved'): void
}>()

const submitting = ref(false)
const form = ref({
  username: '',
  password: '',
  nickname: '',
  status: 'active',
})

const isEdit = ref(false)

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      if (props.admin) {
        isEdit.value = true
        form.value = {
          username: props.admin.username,
          password: '',
          nickname: props.admin.nickname,
          status: props.admin.status,
        }
      } else {
        isEdit.value = false
        form.value = { username: '', password: '', nickname: '', status: 'active' }
      }
    }
  },
  { immediate: true },
)

async function handleSave() {
  submitting.value = true
  try {
    if (isEdit.value && props.admin) {
      const req: UpdateAdminRequest = {
        nickname: form.value.nickname,
        status: form.value.status,
      }
      await updateAdminMgrUser(props.admin.id, req)
      ElMessage.success('管理员已更新')
    } else {
      const req: CreateAdminRequest = {
        username: form.value.username,
        password: form.value.password,
        nickname: form.value.nickname,
      }
      await createAdminMgrUser(req)
      ElMessage.success('管理员已创建')
    }
    emit('saved')
    emit('update:modelValue', false)
  } catch (error) {
    ElMessage.error(readError(error, '操作失败'))
  } finally {
    submitting.value = false
  }
}

function readError(error: unknown, fallback: string) {
  if (typeof error === 'object' && error && 'response' in error) {
    const response = (error as { response?: { data?: { message?: string } } }).response
    return response?.data?.message || fallback
  }
  return fallback
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    :title="isEdit ? '编辑管理员' : '新建管理员'"
    width="500px"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div class="dialog-body">
      <el-form-item label="用户名" class="full-control">
        <el-input v-model="form.username" :disabled="isEdit" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item v-if="!isEdit" label="密码" class="full-control">
        <el-input v-model="form.password" type="password" show-password placeholder="请输入密码（至少6位）" />
      </el-form-item>
      <el-form-item label="昵称" class="full-control">
        <el-input v-model="form.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item v-if="isEdit" label="状态" class="full-control">
        <el-select v-model="form.status" style="width: 100%">
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="disabled" />
        </el-select>
      </el-form-item>
    </div>
    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-body {
  display: grid;
  gap: 16px;
}
.full-control {
  width: 100%;
}
</style>
