<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh, Search } from '@element-plus/icons-vue'
import type {
  Country,
  CreateCountryRequest,
  UpdateCountryRequest,
  CountryFilter,
} from '@/types'
import { countriesApi } from '@/api/countries'

const loading = ref(false)
const list = ref<Country[]>([])
const total = ref(0)

const filter = reactive<Required<CountryFilter>>({
  countryName: '',
  page: 1,
  pageSize: 10,
})

async function fetchList() {
  loading.value = true
  try {
    const res = await countriesApi.getCountriesList(filter)
    const data = await countriesApi.getCountriesList(filter) as any
    const arr = Array.isArray(data) ? data : (data.items ?? [])
    list.value = arr
    total.value = Array.isArray(data) ? data.length : (data.total ?? 0)
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  filter.page = 1
  fetchList()
}

function handleReset() {
  filter.countryName = ''
  filter.page = 1
  fetchList()
}

const dialogRef = ref()
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const dialogLoading = ref(false)

const dialogForm = reactive<CreateCountryRequest & { id?: string }>({
  countryName: '',
  countryIcon: '',
})

const dialogRules = {
  countryName: [{ required: true, message: '名称是必填项', trigger: 'blur' }],
}

function openAddDialog() {
  dialogMode.value = 'create'
  Object.assign(dialogForm, { id: undefined, countryName: '', countryIcon: '' })
  dialogVisible.value = true
}

function openEditDialog(c: Country) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm, { id: c.id, countryName: c.countryName, countryIcon: c.countryIcon || '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!dialogRef.value) return
  await dialogRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    dialogLoading.value = true
    try {
      const payload: CreateCountryRequest = {
        countryName: dialogForm.countryName,
        countryIcon: dialogForm.countryIcon || undefined,
      }
      if (dialogMode.value === 'create') {
        await countriesApi.createCountry(payload)
        ElMessage.success('国家创建成功')
      } else {
        await countriesApi.updateCountry(dialogForm.id!, payload as UpdateCountryRequest)
        ElMessage.success('国家更新成功')
      }
      dialogVisible.value = false
      fetchList()
    } finally {
      dialogLoading.value = false
    }
  })
}

async function handleDelete(c: Country) {
  try {
    await ElMessageBox.confirm(`确定删除「${c.countryName}」吗？`, '确认', {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
    })
  } catch {
    return
  }
  await countriesApi.deleteCountry(c.id)
  ElMessage.success('删除成功')
  fetchList()
}

onMounted(fetchList)
</script>

<template>
  <div class="page-container">
    <div class="page-card">
      <div class="filter-bar">
        <el-input
          v-model="filter.countryName"
          placeholder="按名称搜索"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          <span>搜索</span>
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          <span>重置</span>
        </el-button>

        <div class="filter-spacer" />

        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          <span>新增国家</span>
        </el-button>
      </div>

      <el-table v-loading="loading" :data="list" border stripe>
        <el-table-column label="图标" width="80">
          <template #default="{ row }: { row: Country }">
            <el-image
              v-if="row.countryIcon"
              :src="row.countryIcon"
              :preview-src-list="[row.countryIcon]"
              fit="cover"
              style="width: 32px; height: 32px; border-radius: 4px;"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="countryName" label="名称" min-width="200" />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }: { row: Country }">
            {{ new Date(row.createdAt).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }: { row: Country }">
            <div class="table-actions">
              <el-button size="small" type="primary" plain @click="openEditDialog(row)">
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button size="small" type="danger" plain @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无国家" />
        </template>
      </el-table>

      <el-pagination
        class="pagination"
        v-model:current-page="filter.page"
        v-model:page-size="filter.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="(p: number) => { filter.page = p; fetchList() }"
        @size-change="(s: number) => { filter.pageSize = s; filter.page = 1; fetchList() }"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'create' ? '新增国家' : '编辑国家'"
      width="480px"
      destroy-on-close
    >
      <el-form ref="dialogRef" :model="dialogForm" :rules="dialogRules" label-width="100px">
        <el-form-item label="名称" prop="countryName">
          <el-input v-model="dialogForm.countryName" placeholder="请输入国家名称" />
        </el-form-item>
        <el-form-item label="图标 URL">
          <el-input v-model="dialogForm.countryIcon" placeholder="https://..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="dialogLoading" @click="handleSubmit">
          {{ dialogMode === 'create' ? '创建' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.filter-spacer {
  flex: 1;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
