<script setup>
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import {
  StarFilled,
  CloseOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import { UserPromptApi } from '@/api/userPrompt'

import SavePromptModal from '@/components/SavePromptModal.vue'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'refresh'])

// State
const loading = ref(false)
const promptList = ref([])
const searchKeyword = ref('')
const showSaveModal = ref(false)
const editingPrompt = ref(null)

// Computed
const filteredList = computed(() => {
  if (!searchKeyword.value.trim()) return promptList.value
  const keyword = searchKeyword.value.trim().toLowerCase()
  return promptList.value.filter(item =>
    item.name.toLowerCase().includes(keyword) ||
    (item.content && item.content.toLowerCase().includes(keyword))
  )
})

// Watch
watch(() => props.visible, (newVal) => {
  if (newVal) {
    loadList()
  }
})

// Methods
async function loadList() {
  loading.value = true
  try {
    const res = await UserPromptApi.getUserPromptList()
    if (res.code === 0 && res.data) {
      promptList.value = res.data.map(item => ({
        id: item.id,
        name: item.name,
        content: item.content,
        category: item.category,
        useCount: item.useCount || 0
      }))
    }
  } catch (error) {
    console.error('加载风格列表失败:', error)
    message.error('加载风格列表失败')
  } finally {
    loading.value = false
  }
}

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

function handleCreate() {
  editingPrompt.value = null
  showSaveModal.value = true
}

function handleEdit(item) {
  editingPrompt.value = { ...item }
  showSaveModal.value = true
}

async function handleDelete(id) {
  try {
    await UserPromptApi.deleteUserPrompt(id)
    // 从列表中移除
    const index = promptList.value.findIndex(p => p.id === id)
    if (index !== -1) {
      promptList.value.splice(index, 1)
    }
    message.success('删除成功')
    emit('refresh')
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

function handleSaveSuccess() {
  showSaveModal.value = false
  loadList()
  emit('refresh')
}
</script>

<template>
  <a-modal
    :open="visible"
    title="我创建的"
    :width="700"
    :footer="null"
    @cancel="handleClose"
  >
    <!-- 操作栏 -->
    <div class="action-bar">
      <a-button type="primary" @click="handleCreate">
        <template #icon><PlusOutlined /></template>
        新建风格
      </a-button>
      <a-button @click="loadList" :loading="loading">
        刷新
      </a-button>
    </div>

    <!-- 搜索框 -->
    <div class="search-bar">
      <a-input
        v-model:value="searchKeyword"
        placeholder="搜索风格..."
        allow-clear
      />
    </div>

    <!-- 列表 -->
    <div class="prompt-list" v-if="!loading && filteredList.length > 0">
      <div
        v-for="item in filteredList"
        :key="item.id"
        class="prompt-card"
      >
        <div class="card-header">
          <span class="card-name">{{ item.name }}</span>
          <div class="card-actions">
            <a-button type="link" size="small" @click="handleEdit(item)">
              <EditOutlined /> 编辑
            </a-button>
            <a-popconfirm
              title="确定删除此风格？"
              @confirm="handleDelete(item.id)"
            >
              <a-button type="link" size="small" danger>
                <DeleteOutlined /> 删除
              </a-button>
            </a-popconfirm>
          </div>
        </div>
        <div class="card-content">{{ item.content }}</div>
        <div class="card-footer">
          <span class="card-category" v-if="item.category">{{ item.category }}</span>
          <span class="card-use-count">使用 {{ item.useCount || 0 }} 次</span>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else-if="!loading">
      <StarFilled class="empty-icon" />
      <p class="empty-title">暂无收藏的风格</p>
      <p class="empty-desc">点击"新建风格"创建您的第一个风格</p>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="loading">
      <a-spin />
    </div>

    <!-- 保存弹窗 -->
    <SavePromptModal
      v-model:visible="showSaveModal"
      :prompt="editingPrompt"
      @success="handleSaveSuccess"
    />
  </a-modal>
</template>

<style scoped lang="less">
.action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.search-bar {
  margin-bottom: 16px;
}

.prompt-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.prompt-card {
  padding: 16px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  background: var(--color-surface);
  transition: all 0.2s ease;

  &:hover {
    border-color: var(--color-primary);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.card-name {
  font-weight: 600;
  font-size: 14px;
  color: var(--color-text);
}

.card-actions {
  display: flex;
  gap: 8px;
}

.card-content {
  font-size: 13px;
  color: var(--color-text-secondary);
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.card-category {
  padding: 2px 8px;
  background: rgba(24, 144, 255, 0.1);
  color: #1890ff;
  border-radius: 10px;
}

.card-use-count {
  color: var(--color-text-tertiary);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #f59e0b;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-title {
  font-size: 15px;
  font-weight: 500;
  color: var(--color-text);
  margin: 0 0 8px 0;
}

.empty-desc {
  font-size: 13px;
  color: var(--color-text-secondary);
  margin: 0;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px;
}
</style>
