<template>
  <div class="inquiries-container">
    <h1 class="page-title">合作咨询管理</h1>

    <AdminTableFilter
      v-model:keyword="keyword"
      keyword-placeholder="搜索姓名、公司或联系方式..."
      @search="fetchInquiriesList"
      @reset="resetFilters"
    >
      <template #filters>
        <div class="filter-field">
          <label>状态</label>
          <CustomSelect v-model="filterStatus" :options="statusOptions" style="width: 120px;" />
        </div>
        <div class="filter-field">
          <label>开始日期</label>
          <input v-model="startDate" type="date" class="admin-input" style="width: 150px;" />
        </div>
        <div class="filter-field">
          <label>结束日期</label>
          <input v-model="endDate" type="date" class="admin-input" style="width: 150px;" />
        </div>
      </template>
    </AdminTableFilter>
    
    <div class="table-container">
      <table class="admin-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>公司</th>
            <th>联系方式</th>
            <th>预算</th>
            <th>描述</th>
            <th>状态</th>
            <th>提交时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in inquiries" :key="item.id">
            <td class="table-cell">{{ item.id }}</td>
            <td class="table-cell">{{ item.name }}</td>
            <td class="table-cell">{{ item.company || '-' }}</td>
            <td class="table-cell">
              <div class="flex flex-col text-xs">
                <span class="opacity-70">{{ getContactMethodLabel(item.contactMethod) }}</span>
                <span>{{ item.contactValue }}</span>
              </div>
            </td>
            <td class="table-cell">{{ item.budget || '-' }}</td>
            <td class="table-cell" :title="item.description">
              {{ item.description && item.description.length > 20 ? item.description.substring(0, 20) + '...' : (item.description || '-') }}
            </td>
            <td class="table-cell">
              <span 
                class="px-2 py-1 rounded text-xs"
                :class="getStatusClass(item.status)"
              >
                {{ getStatusLabel(item.status) }}
              </span>
            </td>
            <td class="table-cell">{{ formatCreatedAt(item.createdAt) }}</td>
            <td class="table-cell actions">
              <button
                class="btn-action btn-view"
                @click="openDetail(item)"
                title="查看详情"
              >
                查看
              </button>
              <button 
                v-if="item.status === 0"
                class="btn-action btn-read" 
                @click="updateStatus(item.id!, 1)" 
                title="标记为已读"
              >
                已读
              </button>
              <button 
                v-if="item.status !== 2"
                class="btn-action btn-contact" 
                @click="updateStatus(item.id!, 2)" 
                title="标记为已联系"
              >
                已联系
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-if="inquiries.length === 0" class="empty-state">
        <p>暂无咨询数据</p>
      </div>
    </div>

    <InquiryDetailModal
      v-model:is-open="isDetailModalOpen"
      :inquiry="selectedInquiry"
      @update-status="handleDetailStatusUpdate"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { API_BASE, authFetchJson, fetchInquiriesPaginated, getAuthHeaders, type Inquiry } from '../../services/api'
import { useToast } from '../../composables/useToast'
import InquiryDetailModal from '../../components/admin/InquiryDetailModal.vue'
import AdminTableFilter from '../../components/admin/AdminTableFilter.vue'
import CustomSelect from '../../components/CustomSelect.vue'

const toast = useToast()
const inquiries = ref<Inquiry[]>([])
const isDetailModalOpen = ref(false)
const selectedInquiry = ref<Inquiry | null>(null)
const keyword = ref('')
const filterStatus = ref<number | string>('')
const startDate = ref('')
const endDate = ref('')

const statusOptions = [
  { value: '', label: '全部状态' },
  { value: 0, label: '未读' },
  { value: 1, label: '已读' },
  { value: 2, label: '已联系' },
]

const fetchInquiriesList = async () => {
  try {
    const params: Parameters<typeof fetchInquiriesPaginated>[0] = {
      page: 1,
      pageSize: 500,
      keyword: keyword.value.trim() || undefined,
      startDate: startDate.value || undefined,
      endDate: endDate.value || undefined,
    }
    if (filterStatus.value !== '') {
      params.status = Number(filterStatus.value)
    }
    const data = await fetchInquiriesPaginated(params)
    inquiries.value = data.list
  } catch (error) {
    console.error('Failed to fetch inquiries:', error)
    toast.error('获取咨询列表失败')
  }
}

const resetFilters = () => {
  keyword.value = ''
  filterStatus.value = ''
  startDate.value = ''
  endDate.value = ''
  fetchInquiriesList()
}

const openDetail = (item: Inquiry) => {
  selectedInquiry.value = item
  isDetailModalOpen.value = true
}

const updateStatus = async (id: number, status: number) => {
  try {
    await authFetchJson(`${API_BASE}/admin/inquiries/${id}/status`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify({ status })
    })
    toast.success('状态更新成功')
    await fetchInquiriesList()
    if (selectedInquiry.value?.id === id) {
      selectedInquiry.value = inquiries.value.find(item => item.id === id) || selectedInquiry.value
      if (selectedInquiry.value) {
        selectedInquiry.value.status = status
      }
    }
  } catch (error: any) {
    console.error(error)
    toast.error(error.message || '更新失败')
  }
}

const handleDetailStatusUpdate = async (status: number) => {
  if (!selectedInquiry.value?.id) return
  await updateStatus(selectedInquiry.value.id, status)
}

const formatCreatedAt = (createdAt?: string | number) => {
  if (createdAt === undefined || createdAt === null || createdAt === '') return '-'
  const timestamp = typeof createdAt === 'number' ? createdAt : Number(createdAt)
  if (Number.isNaN(timestamp)) return '-'
  const ms = timestamp > 1e12 ? timestamp : timestamp * 1000
  return new Date(ms).toLocaleString()
}

const getContactMethodLabel = (method: string) => {
  const map: Record<string, string> = {
    'wechat': '微信',
    'email': '邮箱',
    'phone': '电话'
  }
  return map[method] || method
}

const getStatusLabel = (status?: number) => {
  switch (status) {
    case 0: return '未读'
    case 1: return '已读'
    case 2: return '已联系'
    default: return '未知'
  }
}

const getStatusClass = (status?: number) => {
  switch (status) {
    case 0: return 'bg-red-500/20 text-red-400'
    case 1: return 'bg-blue-500/20 text-blue-400'
    case 2: return 'bg-green-500/20 text-green-400'
    default: return 'bg-gray-500/20 text-gray-400'
  }
}

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

<style scoped>
.inquiries-container {
  width: 100%;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: #d4b383;
  margin-bottom: 1.5rem;
  font-family: 'Inter', sans-serif;
}

.table-container {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 0.5rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.admin-table {
  width: 100%;
  border-collapse: collapse;
  font-family: 'Inter', sans-serif;
}

.admin-table thead {
  background: rgba(255, 255, 255, 0.08);
}

.admin-table th {
  padding: 1rem;
  text-align: left;
  font-size: 0.875rem;
  font-weight: 600;
  color: #d4b383;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.admin-table td {
  padding: 1rem;
  font-size: 0.95rem;
  color: rgba(255, 255, 255, 0.8);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.admin-table tr:last-child td {
  border-bottom: none;
}

.admin-table tr:hover {
  background: rgba(255, 255, 255, 0.02);
}

.actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.btn-action {
  padding: 0.35rem 0.65rem;
  border: none;
  border-radius: 0.375rem;
  cursor: pointer;
  font-size: 0.75rem;
  transition: all 0.3s;
}

.btn-view {
  background: rgba(212, 179, 131, 0.12);
  color: rgba(212, 179, 131, 0.95);
}
.btn-view:hover {
  background: rgba(212, 179, 131, 0.22);
}

.btn-read {
  background: rgba(59, 130, 246, 0.1);
  color: rgba(59, 130, 246, 0.8);
}
.btn-read:hover {
  background: rgba(59, 130, 246, 0.2);
}

.btn-contact {
  background: rgba(16, 185, 129, 0.1);
  color: rgba(16, 185, 129, 0.8);
}
.btn-contact:hover {
  background: rgba(16, 185, 129, 0.2);
}

.empty-state {
  padding: 3rem;
  text-align: center;
  color: rgba(255, 255, 255, 0.5);
}
</style>
