<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="showCreateDialog = 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="companies" stripe border class="w-full shadow-sm">
      <template #empty><el-empty description="目前無公司" /></template>
      <el-table-column prop="company_key" label="Company Key" width="220" />
      <el-table-column prop="name" label="公司名稱" min-width="220" />
      <el-table-column prop="status" label="狀態" width="110" />
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">編輯</el-button>
          <el-button size="small" @click="openSites(row)">查看站台</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">刪除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showCreateDialog" title="新增公司" width="560px" @close="resetCreateForm">
      <el-form ref="createFormRef" :model="createForm" :rules="rules" label-width="120px">
        <el-form-item label="公司名稱" prop="name"><el-input v-model="createForm.name" /></el-form-item>
        <el-form-item label="狀態">
          <el-select v-model="createForm.status" style="width: 100%">
            <el-option label="active" value="active" />
            <el-option label="inactive" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="creating" @click="handleCreate">建立</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showEditDialog" title="編輯公司" width="560px" @close="resetEditForm">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="Company Key"><el-input :model-value="editForm.company_key" disabled /></el-form-item>
        <el-form-item label="公司名稱"><el-input v-model="editForm.name" /></el-form-item>
        <el-form-item label="狀態">
          <el-select v-model="editForm.status" style="width: 100%">
            <el-option label="active" value="active" />
            <el-option label="inactive" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleEdit">儲存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showSitesDialog" :title="`站台列表：${selectedCompanyDisplayName}`" width="960px">
      <el-table :data="companySites" border stripe v-loading="sitesLoading">
        <template #empty><el-empty description="此公司目前沒有站台" /></template>
        <el-table-column prop="site_key" label="Site Key" width="210" />
        <el-table-column prop="display_name" label="站台名稱" min-width="200" />
        <el-table-column prop="domain" label="Domain" min-width="220" />
        <el-table-column prop="status" label="狀態" width="110" />
      </el-table>
      <template #footer>
        <el-button @click="showSitesDialog = false">關閉</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getCompanies, createCompany, updateCompany, deleteCompany, getCompanySites } from '@/api/companies'

const companies = ref([])
const loading = ref(false)
const error = ref(false)
const errorMsg = ref('')

const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const creating = ref(false)
const saving = ref(false)
const createFormRef = ref()

const createForm = ref({ name: '', status: 'active' })
const editForm = ref({ company_key: '', name: '', status: 'active' })
const rules = {
  name: [{ required: true, message: '請輸入公司名稱', trigger: 'blur' }]
}

const showSitesDialog = ref(false)
const sitesLoading = ref(false)
const selectedCompanyDisplayName = ref('')
const companySites = ref([])

async function load() {
  loading.value = true
  error.value = false
  try {
    const res = await getCompanies()
    companies.value = res.data?.items || []
  } catch (err) {
    error.value = true
    errorMsg.value = err.response?.data?.detail || '載入公司失敗'
  } finally {
    loading.value = false
  }
}

function resetCreateForm() {
  createForm.value = { name: '', status: 'active' }
}

function openEdit(row) {
  editForm.value = {
    company_key: row.company_key,
    name: row.name || '',
    status: row.status || 'active'
  }
  showEditDialog.value = true
}

function resetEditForm() {
  editForm.value = { company_key: '', name: '', status: 'active' }
}

async function handleCreate() {
  const valid = await createFormRef.value.validate().catch(() => false)
  if (!valid) return
  creating.value = true
  try {
    const res = await createCompany(createForm.value)
    ElMessage.success(`新增成功：${res.data?.company_key || ''}`)
    showCreateDialog.value = false
    resetCreateForm()
    await load()
  } catch (err) {
    ElMessage.error(err.response?.data?.detail || '新增公司失敗')
  } finally {
    creating.value = false
  }
}

async function handleEdit() {
  saving.value = true
  try {
    await updateCompany(editForm.value.company_key, {
      name: editForm.value.name,
      status: editForm.value.status
    })
    ElMessage.success('更新成功')
    showEditDialog.value = false
    await load()
  } catch (err) {
    ElMessage.error(err.response?.data?.detail || '更新公司失敗')
  } finally {
    saving.value = false
  }
}

async function openSites(row) {
  showSitesDialog.value = true
  selectedCompanyDisplayName.value = `${row.name || row.company_key} (${row.company_key})`
  sitesLoading.value = true
  try {
    const res = await getCompanySites(row.company_key)
    companySites.value = res.data?.sites || []
  } catch (_err) {
    ElMessage.error('載入站台列表失敗')
    companySites.value = []
  } finally {
    sitesLoading.value = false
  }
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(
      `確認刪除公司 ${row.name || row.company_key}（${row.company_key}）？`,
      '刪除確認',
      { type: 'warning' }
    )
    await deleteCompany(row.company_key)
    ElMessage.success('刪除成功')
    await load()
  } catch (err) {
    if (err === 'cancel') return
    ElMessage.error(err.response?.data?.detail || '刪除公司失敗')
  }
}

onMounted(load)
</script>
