<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh, Search, Rank } 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 {
    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()
}

// ─── 拖拽排序：松开即按新顺序全量保存（sortOrder = 下标） ───
const dragIndex = ref<number | null>(null)
const sorting = ref(false)

function onRowDragStart(index: number) {
  dragIndex.value = index
}

async function onRowDrop(index: number) {
  const from = dragIndex.value
  dragIndex.value = null
  if (from === null || from === index || sorting.value) return
  const next = [...list.value]
  const [moved] = next.splice(from, 1)
  next.splice(index, 0, moved)
  list.value = next
  sorting.value = true
  try {
    const updated = await countriesApi.sortCountries(
      next.map((c, i) => ({ id: String(c.id), sortOrder: i })),
    )
    const arr = Array.isArray(updated) ? updated : []
    if (arr.length) list.value = arr
    ElMessage.success('排序已保存')
  } catch {
    ElMessage.error('排序保存失败')
    await fetchList()
  } finally {
    sorting.value = false
  }
}

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>

      <ul v-loading="loading" class="country-list">
        <li
          v-for="(row, index) in list"
          :key="row.id"
          class="country-row"
          :class="{ 'is-dragging': dragIndex === index }"
          draggable="true"
          title="拖拽调整顺序，松开即保存"
          @dragstart="onRowDragStart(index)"
          @dragover.prevent
          @drop="onRowDrop(index)"
          @dragend="dragIndex = null"
        >
          <el-icon class="drag-handle"><Rank /></el-icon>
          <el-image
            v-if="row.countryIcon"
            :src="row.countryIcon"
            :preview-src-list="[row.countryIcon]"
            fit="cover"
            class="row-icon"
          />
          <span v-else class="row-icon row-icon-placeholder">-</span>
          <span class="row-name">{{ row.countryName }}</span>
          <span class="row-time">{{ new Date(row.createdAt).toLocaleString() }}</span>
          <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>
        </li>
        <li v-if="!loading && !list.length" class="country-empty">暂无国家</li>
      </ul>
    </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;
}

.country-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.country-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 16px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-top: none;
  cursor: grab;
}

.country-row:first-child {
  border-top: 1px solid var(--el-border-color-lighter);
  border-radius: 4px 4px 0 0;
}

.country-row:last-child {
  border-radius: 0 0 4px 4px;
}

.country-row:only-child {
  border-radius: 4px;
}

.country-row.is-dragging {
  opacity: 0.5;
}

.country-row:hover {
  background: var(--el-fill-color-light);
}

.drag-handle {
  color: var(--el-text-color-secondary);
  font-size: 16px;
}

.row-icon {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  flex: none;
}

.row-icon-placeholder {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  border: 1px dashed var(--el-border-color);
}

.row-name {
  font-weight: 500;
}

.row-time {
  margin-left: auto;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}

.table-actions {
  flex: none;
}

.country-empty {
  padding: 32px 0;
  text-align: center;
  color: var(--el-text-color-secondary);
}
</style>
