<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="sites" stripe border class="w-full shadow-sm">
      <el-empty v-if="sites.length === 0" slot="empty" description="目前無站台" />
      <el-table-column prop="site_key" label="Site Key" width="160" />
      <el-table-column prop="company_key" label="Company 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 :model="form" label-width="120px">
        <el-form-item label="Site Key">
          <el-input v-model="form.site_key" placeholder="site-001" />
        </el-form-item>
        <el-form-item label="Company Key">
          <el-input v-model="form.company_key" placeholder="company-001" />
        </el-form-item>
        <el-form-item label="名稱">
          <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 { getSites, createSite } from '@/api/sites'

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

const form = ref({ site_key: '', company_key: '', name: '' })

async function load() {
  loading.value = true
  error.value = false
  try {
    const res = await getSites()
    sites.value = res.data || []
  } catch (err) {
    error.value = true
    errorMsg.value = '載入失敗，請稍後再試'
  } finally {
    loading.value = false
  }
}

function resetForm() {
  form.value = { site_key: '', company_key: '', name: '' }
}

async function handleCreate() {
  if (!form.value.site_key || !form.value.company_key || !form.value.name) {
    ElMessage.warning('請填寫完整資訊')
    return
  }
  submitting.value = true
  try {
    await createSite(form.value)
    ElMessage.success('新增成功')
    showDialog.value = false
    resetForm()
    await load()
  } catch (err) {
    ElMessage.error('新增失敗，請稍後再試')
  } finally {
    submitting.value = false
  }
}

onMounted(load)
</script>
