<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <h2 class="text-xl font-bold text-gray-800">模組管理</h2>
      <el-button type="primary" @click="showDialog = true" :icon="Plus">新增模組</el-button>
    </div>

    <el-alert
      v-if="error"
      :title="errorMsg"
      type="error"
      show-icon
      :closable="false"
      class="mb-4"
    />

    <el-skeleton v-if="loading" :rows="4" animated />

    <el-table v-else :data="modules" stripe border class="w-full shadow-sm">
      <template #empty><el-empty description="目前無模組" /></template>
      <el-table-column prop="system_key" label="System Key" width="140" />
      <el-table-column prop="module_key" label="Module Key" width="160" />
      <el-table-column prop="name" label="名稱" min-width="180" />
    </el-table>

    <!-- 新增 Dialog -->
    <el-dialog v-model="showDialog" title="新增模組" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="System Key" prop="system_key">
          <el-input v-model="form.system_key" placeholder="mkt" />
        </el-form-item>
        <el-form-item label="Module Key" prop="module_key">
          <el-input v-model="form.module_key" placeholder="campaign" />
        </el-form-item>
        <el-form-item label="名稱" prop="name">
          <el-input v-model="form.name" placeholder="行銷活動" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleCreate">確認</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getModules, createModule } from '@/api/modules'

const modules = ref([])
const loading = ref(false)
const error = ref(false)
const errorMsg = ref('')
const showDialog = ref(false)
const submitting = ref(false)
const formRef = ref()

const form = ref({ system_key: '', module_key: '', name: '' })
const rules = {
  system_key: [{ required: true, message: '請輸入 System Key', trigger: 'blur' }],
  module_key: [{ required: true, message: '請輸入 Module Key', trigger: 'blur' }],
  name: [{ required: true, message: '請輸入名稱', trigger: 'blur' }]
}

async function load() {
  loading.value = true
  error.value = false
  try {
    const res = await getModules()
    modules.value = res.data?.items || []
  } catch (err) {
    error.value = true
    errorMsg.value = err.response?.status === 422
      ? '缺少管理員 API 認證，請檢查前端 .env.development'
      : '載入失敗，請稍後再試'
  } finally {
    loading.value = false
  }
}

function resetForm() {
  form.value = { system_key: '', module_key: '', name: '' }
}

async function handleCreate() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  submitting.value = true
  try {
    await createModule(form.value)
    ElMessage.success('新增成功')
    showDialog.value = false
    resetForm()
    await load()
  } catch (err) {
    ElMessage.error('新增失敗，請稍後再試')
  } finally {
    submitting.value = false
  }
}

onMounted(load)
</script>
