<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 {
  Tag,
  TagGroup,
  CreateTagRequest,
  UpdateTagRequest,
  TagFilter,
} from '@/types'
import { tagsApi } from '@/api/tags'
import { tagGroupsApi } from '@/api/tag-groups'

const loading = ref(false)
const list = ref<Tag[]>([])
const total = ref(0)
const allGroups = ref<TagGroup[]>([])

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

async function fetchList() {
  loading.value = true
  try {
    const res = await tagsApi.getTagsList(filter)
    const data = await tagsApi.getTagsList(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
  }
}

async function loadGroups() {
  allGroups.value = await tagGroupsApi.getTagGroupsList()
}

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

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

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

const dialogForm = reactive<CreateTagRequest & { id?: string; tagGroupId?: number | null }>({
  id: undefined,
  tagName: '',
  tagColor: '#ff6800',
  tagFontColor: '#ffffff',
  timing: '',
  tagGroupId: null,
})

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

function openAddDialog() {
  dialogMode.value = 'create'
  Object.assign(dialogForm, { id: undefined, tagName: '', tagColor: '#ff6800', tagFontColor: '#ffffff', timing: '', tagGroupId: null })
  dialogVisible.value = true
}

function openEditDialog(t: Tag) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm, {
    id: t.id,
    tagName: t.tagName,
    tagColor: t.tagColor || '#ff6800',
    tagFontColor: t.tagFontColor || '#ffffff',
    timing: t.timing || '',
    tagGroupId: t.tagGroupId ? Number(t.tagGroupId) : null,
  })
  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: CreateTagRequest = {
        tagName: dialogForm.tagName,
        tagColor: dialogForm.tagColor || undefined,
        tagFontColor: dialogForm.tagFontColor || undefined,
        timing: dialogForm.timing || undefined,
        tagGroupId: dialogForm.tagGroupId ?? undefined,
      }
      if (dialogMode.value === 'create') {
        await tagsApi.createTag(payload)
        ElMessage.success('标签创建成功')
      } else {
        await tagsApi.updateTag(dialogForm.id!, payload as UpdateTagRequest)
        ElMessage.success('标签更新成功')
      }
      dialogVisible.value = false
      fetchList()
    } finally {
      dialogLoading.value = false
    }
  })
}

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

onMounted(() => {
  fetchList()
  loadGroups()
})
</script>

<template>
  <div class="page-container">
    <div class="page-card">
      <div class="filter-bar">
        <el-input
          v-model="filter.tagName"
          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="120">
          <template #default="{ row }: { row: Tag }">
            <span
              v-if="row.tagColor"
              class="tag-preview"
              :style="{ background: row.tagColor, color: row.tagFontColor || '#fff' }"
            >{{ row.tagName }}</span>
            <el-tag v-else effect="plain">{{ row.tagName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tagName" label="名称" min-width="200" />
        <el-table-column label="背景色" width="140">
          <template #default="{ row }: { row: Tag }">
            <div class="color-cell">
              <span class="color-swatch" :style="{ background: row.tagColor || '#d1d5db' }" />
              <span class="color-hex">{{ row.tagColor || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="字体色" width="140">
          <template #default="{ row }: { row: Tag }">
            <div class="color-cell">
              <span class="color-swatch" :style="{ background: row.tagFontColor || '#d1d5db' }" />
              <span class="color-hex">{{ row.tagFontColor || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属分组" min-width="140">
          <template #default="{ row }: { row: Tag }">
            <span v-if="row.tagGroup">{{ row.tagGroup.groupName }}</span>
            <span v-else style="color: #999;">未分组</span>
          </template>
        </el-table-column>
        <el-table-column prop="timing" label="定时" min-width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }: { row: Tag }">
            <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="tagName">
          <el-input v-model="dialogForm.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="背景色">
          <el-color-picker v-model="dialogForm.tagColor" />
          <span class="color-readout">{{ dialogForm.tagColor }}</span>
        </el-form-item>
        <el-form-item label="字体色">
          <el-color-picker v-model="dialogForm.tagFontColor" />
          <span class="color-readout">{{ dialogForm.tagFontColor }}</span>
        </el-form-item>
        <el-form-item label="所属分组">
          <el-select v-model="dialogForm.tagGroupId" clearable placeholder="未分组" style="width: 100%">
            <el-option
              v-for="g in allGroups"
              :key="g.id"
              :label="g.groupName"
              :value="Number(g.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="定时">
          <el-input v-model="dialogForm.timing" placeholder="例如 9:00-12:00" />
        </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;
}

.color-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-swatch {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
}

.color-hex {
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  font-size: 12px;
  color: #6b7280;
}

.color-readout {
  margin-left: 12px;
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  font-size: 12px;
  color: #6b7280;
}

.tag-preview {
  display: inline-block;
  padding: 2px 12px;
  border-radius: 4px;
  font-size: 13px;
  white-space: nowrap;
}
</style>
