<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTagStore } from '@/stores/tag'
import type { Tag } from '@/types'
import TagBadge from './TagBadge.vue'

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
}>()

const tagStore = useTagStore()
const tags = computed(() => tagStore.sortedTags)

const editingTag = ref<Tag | null>(null)
const showEditDialog = ref(false)
const showCreateDialog = ref(false)
const loading = ref(false)

const editForm = reactive({
  name: '',
  color: '',
  icon: ''
})

const createForm = reactive({
  name: '',
  color: '#667eea',
  icon: ''
})

// 预设颜色
const presetColors = [
  '#667eea', '#764ba2', '#f56c6c', '#e6a23c', '#67c23a',
  '#409eff', '#909399', '#ff6b6b', '#4ecdc4', '#45b7d1',
  '#96c93d', '#f7dc6f', '#bb8fce', '#85c1e9', '#f8b500'
]

watch(() => props.visible, (val) => {
  if (val) {
    tagStore.fetchTags()
  }
})

function handleClose() {
  emit('update:visible', false)
}

function handleEdit(tag: Tag) {
  editingTag.value = tag
  editForm.name = tag.name
  editForm.color = tag.color || ''
  editForm.icon = tag.icon || ''
  showEditDialog.value = true
}

async function handleSaveEdit() {
  if (!editingTag.value) return
  if (!editForm.name.trim()) {
    ElMessage.warning('请输入标签名称')
    return
  }

  loading.value = true
  try {
    const response = await tagStore.updateTag(editingTag.value.id, {
      name: editForm.name.trim(),
      color: editForm.color || undefined,
      icon: editForm.icon || undefined
    })
    if (response.success) {
      ElMessage.success('更新成功')
      showEditDialog.value = false
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch {
    ElMessage.error('更新失败')
  } finally {
    loading.value = false
  }
}

function handleCreate() {
  createForm.name = ''
  createForm.color = '#667eea'
  createForm.icon = ''
  showCreateDialog.value = true
}

async function handleSaveCreate() {
  if (!createForm.name.trim()) {
    ElMessage.warning('请输入标签名称')
    return
  }

  loading.value = true
  try {
    const response = await tagStore.createTag(
      createForm.name.trim(),
      createForm.color || undefined,
      createForm.icon || undefined
    )
    if (response.success) {
      ElMessage.success('创建成功')
      showCreateDialog.value = false
    } else {
      ElMessage.error(response.message || '创建失败')
    }
  } catch {
    ElMessage.error('创建失败')
  } finally {
    loading.value = false
  }
}

async function handleDelete(tag: Tag) {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签 "${tag.name}" 吗？该标签将从所有书签中移除。`,
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await tagStore.deleteTag(tag.id)
    if (response.success) {
      ElMessage.success('删除成功')
    }
  } catch {
    // 取消
  }
}
</script>

<template>
  <el-drawer
    :model-value="visible"
    title="标签管理"
    direction="rtl"
    size="400px"
    @close="handleClose"
  >
    <div class="tag-manager">
      <!-- 创建按钮 -->
      <div class="manager-header">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建标签
        </el-button>
      </div>

      <!-- 标签列表 -->
      <div class="tag-list">
        <div
          v-for="tag in tags"
          :key="tag.id"
          class="tag-list-item"
        >
          <TagBadge :tag="tag" size="default" />
          <span class="tag-count">{{ tag.count }} 个书签</span>
          <div class="tag-actions">
            <el-button size="small" @click="handleEdit(tag)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(tag)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>

        <el-empty v-if="tags.length === 0" description="暂无标签" />
      </div>
    </div>

    <!-- 编辑标签弹窗 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑标签"
      width="400px"
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="颜色">
          <div class="color-picker">
            <div class="preset-colors">
              <span
                v-for="color in presetColors"
                :key="color"
                class="color-item"
                :class="{ active: editForm.color === color }"
                :style="{ backgroundColor: color }"
                @click="editForm.color = color"
              />
            </div>
            <el-color-picker v-model="editForm.color" show-alpha />
          </div>
        </el-form-item>
        <el-form-item label="预览">
          <TagBadge
            v-if="editForm.name"
            :tag="{ id: '', name: editForm.name, color: editForm.color, icon: editForm.icon, order: 0, count: 0 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSaveEdit">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 创建标签弹窗 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新建标签"
      width="400px"
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="createForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="颜色">
          <div class="color-picker">
            <div class="preset-colors">
              <span
                v-for="color in presetColors"
                :key="color"
                class="color-item"
                :class="{ active: createForm.color === color }"
                :style="{ backgroundColor: color }"
                @click="createForm.color = color"
              />
            </div>
            <el-color-picker v-model="createForm.color" show-alpha />
          </div>
        </el-form-item>
        <el-form-item label="预览">
          <TagBadge
            v-if="createForm.name"
            :tag="{ id: '', name: createForm.name, color: createForm.color, icon: createForm.icon, order: 0, count: 0 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSaveCreate">
          创建
        </el-button>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<style lang="scss" scoped>
.tag-manager {
  .manager-header {
    margin-bottom: 20px;
  }

  .tag-list {
    .tag-list-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      border-radius: 8px;
      transition: all 0.2s;

      &:hover {
        background: #f5f5f5;

        .tag-actions {
          opacity: 1;
        }
      }

      .tag-count {
        flex: 1;
        color: #999;
        font-size: 13px;
      }

      .tag-actions {
        display: flex;
        gap: 8px;
        opacity: 0;
        transition: opacity 0.2s;
      }
    }
  }
}

.color-picker {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .preset-colors {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .color-item {
      width: 24px;
      height: 24px;
      border-radius: 4px;
      cursor: pointer;
      border: 2px solid transparent;
      transition: all 0.2s;

      &:hover {
        transform: scale(1.1);
      }

      &.active {
        border-color: #333;
      }
    }
  }
}
</style>
