<template>
  <el-container class="layout-container" style="height: 100vh">
    <el-aside width="200px" style="background-color: #545c64">
      <div class="logo">BID MONITOR</div>
      <el-menu
        active-text-color="#ffd04b"
        background-color="#545c64"
        class="el-menu-vertical-demo"
        default-active="1"
        text-color="#fff"
        @select="handleSelect"
      >
        <el-menu-item index="1">
          <el-icon><DataBoard /></el-icon>
          <span>Dashboard</span>
        </el-menu-item>
        <el-menu-item index="2">
          <el-icon><Document /></el-icon>
          <span>Bids</span>
        </el-menu-item>
        <el-menu-item index="3">
          <el-icon><Setting /></el-icon>
          <span>Keywords</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header style="text-align: right; font-size: 12px">
        <span>Admin</span>
      </el-header>

      <el-main>
        <div v-if="activeIndex === '1'">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2 style="margin: 0;">Dashboard</h2>
            <el-button type="primary" :loading="crawling" @click="handleCrawl">
              <el-icon style="margin-right: 5px"><Refresh /></el-icon>
              立刻抓取
            </el-button>
          </div>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-card class="box-card" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>High Priority Bids</span>
                    <el-tag type="danger">Top 10</el-tag>
                  </div>
                </template>
                <el-table :data="highPriorityBids" style="width: 100%" size="small">
                  <el-table-column prop="title" label="Title">
                    <template #default="scope">
                      <a :href="scope.row.url" target="_blank">{{ scope.row.title }}</a>
                    </template>
                  </el-table-column>
                  <el-table-column prop="source" label="Source" width="120" />
                  <el-table-column prop="publishDate" label="Date" width="120">
                    <template #default="scope">{{ formatDate(scope.row.publishDate) }}</template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
          <el-divider />
          <h3>Today's Bids</h3>
          <el-table :data="bids" v-loading="loading" style="width: 100%">
              <el-table-column prop="title" label="Title">
                <template #default="scope">
                  <a :href="scope.row.url" target="_blank">{{ scope.row.title }}</a>
                </template>
              </el-table-column>
              <el-table-column prop="source" label="Source" width="150" />
              <el-table-column prop="publishDate" label="Date" width="150">
                <template #default="scope">{{ formatDate(scope.row.publishDate) }}</template>
              </el-table-column>
          </el-table>
        </div>

        <div v-if="activeIndex === '2'">
          <h2>All Bids</h2>
           <el-table :data="bids" v-loading="loading" style="width: 100%">
              <el-table-column prop="title" label="Title">
                <template #default="scope">
                  <a :href="scope.row.url" target="_blank">{{ scope.row.title }}</a>
                </template>
              </el-table-column>
              <el-table-column prop="source" label="Source" width="150" />
              <el-table-column prop="publishDate" label="Date" width="150">
                <template #default="scope">{{ formatDate(scope.row.publishDate) }}</template>
              </el-table-column>
          </el-table>
        </div>

        <div v-if="activeIndex === '3'">
          <div class="card-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
             <h2>Keyword Management</h2>
             <el-button type="primary" @click="dialogVisible = true">Add Keyword</el-button>
          </div>
         
          <el-table :data="keywords" v-loading="loading" style="width: 100%">
            <el-table-column prop="word" label="Keyword" />
            <el-table-column prop="weight" label="Weight" />
            <el-table-column label="Action">
              <template #default="scope">
                <el-button type="danger" size="small" @click="handleDeleteKeyword(scope.row.id)">Delete</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>

    <el-dialog v-model="dialogVisible" title="Add Keyword" width="30%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="Keyword">
          <el-input v-model="form.word" />
        </el-form-item>
        <el-form-item label="Weight">
           <el-input-number v-model="form.weight" :min="1" :max="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleAddKeyword">Confirm</el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { DataBoard, Document, Setting, Refresh } from '@element-plus/icons-vue'

const activeIndex = ref('1')
const bids = ref<any[]>([])
const highPriorityBids = ref<any[]>([])
const keywords = ref<any[]>([])
const loading = ref(false)
const crawling = ref(false)
const dialogVisible = ref(false)

const form = reactive({
  word: '',
  weight: 1
})

const handleSelect = (key: string) => {
  activeIndex.value = key
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString()
}

const fetchData = async () => {
  loading.value = true
  try {
    const [bidsRes, highRes, kwRes] = await Promise.all([
      axios.get('/api/bids'),
      axios.get('/api/bids/high-priority'),
      axios.get('/api/keywords')
    ])
    bids.value = bidsRes.data.items
    highPriorityBids.value = highRes.data
    keywords.value = kwRes.data
  } catch (error) {
    ElMessage.error('Failed to fetch data')
  } finally {
    loading.value = false
  }
}

const handleCrawl = async () => {
  crawling.value = true
  try {
    await axios.post('/api/crawler/run')
    ElMessage.success('Crawl completed successfully')
    fetchData() // Refresh data after crawl
  } catch (error) {
    ElMessage.error('Failed to run crawl task')
  } finally {
    crawling.value = false
  }
}

const handleAddKeyword = async () => {
  if (!form.word) {
    ElMessage.warning('Please enter a keyword')
    return
  }
  try {
    await axios.post('/api/keywords', form)
    ElMessage.success('Keyword added')
    dialogVisible.value = false
    form.word = ''
    form.weight = 1
    fetchData()
  } catch (error) {
    ElMessage.error('Failed to add keyword')
  }
}

const handleDeleteKeyword = async (id: string) => {
  try {
    await axios.delete(`/api/keywords/${id}`)
    ElMessage.success('Keyword deleted')
    fetchData()
  } catch (error) {
    ElMessage.error('Failed to delete keyword')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.layout-container .el-header {
  background-color: #fff;
  color: var(--el-text-color-primary);
  line-height: 60px;
  border-bottom: 1px solid #eee;
}
.layout-container .el-aside {
  color: var(--el-text-color-primary);
}
.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  color: white;
  font-weight: bold;
  font-size: 18px;
  background-color: #434a50;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>