<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
      <h2 style="margin: 0;">All Bids</h2>
      <el-select v-model="selectedSource" placeholder="Filter by Source" clearable style="width: 200px" @change="handleSourceChange">
        <el-option
          v-for="source in sourceOptions"
          :key="source"
          :label="source"
          :value="source"
        />
      </el-select>
    </div>
    <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="200" />
      <el-table-column prop="publishDate" label="Date" width="150">
        <template #default="scope">{{ formatDate(scope.row.publishDate) }}</template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      style="margin-top: 20px; justify-content: flex-end;"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

interface Props {
  bids: any[]
  sourceOptions: string[]
  loading: boolean
  total: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  fetch: [page: number, limit: number, source?: string]
}>()

const selectedSource = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

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

const handleSourceChange = () => {
  currentPage.value = 1
  emit('fetch', currentPage.value, pageSize.value, selectedSource.value || undefined)
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  emit('fetch', currentPage.value, pageSize.value, selectedSource.value || undefined)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  emit('fetch', currentPage.value, pageSize.value, selectedSource.value || undefined)
}
</script>

<style scoped>
a {
  text-decoration: none;
  color: inherit;
}

a:hover {
  color: #409eff;
}
</style>
