<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { CopyDocument, Search } from '@element-plus/icons-vue'

import { fetchOrders, type Order } from '@/features/orders'
import { useSessionStore } from '@/stores/session'
import { orderStatusLabel } from '@/utils/statusLabels'
import { formatDateTime } from '@/utils/time'

const loading = ref(false)
const orders = ref<Order[]>([])
const payingOrderId = ref<number | null>(null)
const session = useSessionStore()
const route = useRoute()
const router = useRouter()
const searchKeyword = ref('')
const statusTabs = [
  { key: 'all', label: '全部' },
  { key: 'pending_payment', label: '待支付' },
  { key: 'pending_handoff', label: '待交接' },
  { key: 'renting', label: '使用中' },
  { key: 'pending_checkout_confirm', label: '待结账' },
  { key: 'completed', label: '已完成' },
]
const tabKeys = new Set(statusTabs.map((item) => item.key))
const activeTab = ref(readTab(route.query.tab))

const displayOrders = computed(() => {
  let filtered = orders.value

  if (activeTab.value !== 'all') {
    filtered = filtered.filter((order) => order.status === activeTab.value)
  }

  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    filtered = filtered.filter((order) =>
      order.order_no.toLowerCase().includes(keyword) ||
      order.title.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

const tabCounts = computed(() => {
  const counts: Record<string, number> = { all: orders.value.length }
  statusTabs.forEach((tab) => {
    if (tab.key !== 'all') {
      counts[tab.key] = orders.value.filter((order) => order.status === tab.key).length
    }
  })
  return counts
})

onMounted(loadOrders)

watch(
  () => route.query.tab,
  (tab) => {
    activeTab.value = readTab(tab)
  },
)

function readTab(tab: unknown) {
  const value = typeof tab === 'string' ? tab : 'all'
  return tabKeys.has(value) ? value : 'all'
}

function handleTabChange(tab: string | number) {
  const nextTab = readTab(String(tab))
  router.replace({ path: '/orders', query: nextTab === 'all' ? {} : { tab: nextTab } })
}

async function loadOrders() {
  loading.value = true
  try {
    orders.value = await fetchOrders()
  } finally {
    loading.value = false
  }
}

async function handlePay(order: Order) {
  payingOrderId.value = order.id
  try {
    await router.push(`/orders/${order.id}?pay=1`)
  } catch (error) {
    ElMessage.error(readError(error, '打开支付失败'))
  } finally {
    payingOrderId.value = null
  }
}

function readError(error: unknown, fallback: string) {
  if (typeof error === 'object' && error && 'response' in error) {
    const response = (error as { response?: { data?: { message?: string } } }).response
    return response?.data?.message || fallback
  }
  return fallback
}

function orderRole(order: Order) {
  if (order.renter_id === session.userId) return '租客'
  if (order.owner_id === session.userId) return '号主'
  return '-'
}

function isRenter(order: Order) {
  return order.renter_id === session.userId
}

function isOwner(order: Order) {
  return order.owner_id === session.userId
}

function amountLabel(order: Order) {
  return isRenter(order) ? '支付租金' : '预计租金'
}

function orderRentAmount(order: Order) {
  if (isOwner(order)) return Number(order.owner_rent_amount ?? order.display_amount ?? 0)
  if (isRenter(order)) return Number(order.rent_amount ?? order.display_amount ?? 0)
  return Number(order.display_amount ?? 0)
}

function ownerActualIncome(order: Order) {
  if (!isOwner(order)) return null
  const value = order.checkout?.owner_income_amount
  return typeof value === 'number' ? value : null
}

function money(value: unknown) {
  return Math.round(Number(value || 0))
}

function shortenOrderNo(orderNo: string) {
  if (orderNo.length <= 20) return orderNo
  return `${orderNo.slice(0, 12)}...${orderNo.slice(-6)}`
}

async function copyOrderNo(orderNo: string) {
  try {
    await navigator.clipboard.writeText(orderNo)
    ElMessage.success('订单号已复制')
  } catch {
    ElMessage.error('复制失败')
  }
}

function getPaymentDeadline(order: Order) {
  if (order.status !== 'pending_payment' || !order.created_at) return null
  const created = new Date(order.created_at)
  const deadline = new Date(created.getTime() + 30 * 60 * 1000)
  return deadline
}

function getCountdownMinutes(order: Order) {
  const deadline = getPaymentDeadline(order)
  if (!deadline) return 0
  const now = new Date()
  const diff = deadline.getTime() - now.getTime()
  return Math.max(0, Math.ceil(diff / 60000))
}
</script>

<template>
  <section class="page">
    <div class="page-header">
      <p class="eyebrow">ORDERS</p>
      <h1>我的订单</h1>
      <p>跟踪待支付、待交接、使用中、待归还、申诉中和已完成订单。</p>
    </div>

    <div class="orders-toolbar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索订单号 / 账号 / 起始数字"
        :prefix-icon="Search"
        clearable
        class="search-input"
      />
    </div>

    <el-tabs v-model="activeTab" class="order-tabs" @tab-change="handleTabChange">
      <el-tab-pane v-for="tab in statusTabs" :key="tab.key" :name="tab.key">
        <template #label>
          <span class="tab-label">
            {{ tab.label }}
            <span v-if="(tabCounts?.[tab.key] ?? 0) > 0" class="tab-count">{{ tabCounts?.[tab.key] }}</span>
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>

    <div v-if="displayOrders.length === 0 && !loading" class="empty-state">
      <el-empty :description="searchKeyword ? '没有找到匹配的订单' : '暂无订单'" />
    </div>

    <div v-else class="orders-container">
      <el-table v-loading="loading" class="table-panel orders-table" :data="displayOrders">
        <el-table-column label="订单号" min-width="180">
          <template #default="{ row }">
            <div class="order-no-cell">
              <span class="order-no-text" :title="row.order_no">{{ shortenOrderNo(row.order_no) }}</span>
              <el-icon class="copy-icon" @click="copyOrderNo(row.order_no)">
                <CopyDocument />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="账号" min-width="180" />
        <el-table-column label="金额" width="132">
          <template #default="{ row }">
            <div class="amount-cell">
              <span class="amount-value">¥{{ money(orderRentAmount(row)) }}</span>
              <span class="amount-label">{{ amountLabel(row) }}</span>
              <span v-if="ownerActualIncome(row) !== null" class="amount-sub">实际到手 ¥{{ money(ownerActualIncome(row)) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="押金" width="100">
          <template #default="{ row }">¥{{ money(row.deposit_amount) }}</template>
        </el-table-column>
        <el-table-column label="身份" width="80">
          <template #default="{ row }">
            <el-tag :type="isRenter(row) ? 'primary' : 'success'" size="small">
              {{ orderRole(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="140">
          <template #default="{ row }">
            <div class="status-cell">
              <span>{{ orderStatusLabel(row.status) }}</span>
              <span v-if="row.status === 'pending_payment' && getCountdownMinutes(row) > 0" class="countdown-badge">
                {{ getCountdownMinutes(row) }}分钟后超时
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="row.status === 'pending_payment'"
                size="small"
                type="primary"
                :disabled="row.renter_id !== session.userId"
                :loading="payingOrderId === row.id"
                @click="handlePay(row)"
              >
                使用中
              </el-button>
              <RouterLink :to="`/orders/${row.id}`">
                <el-button size="small">详情</el-button>
              </RouterLink>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="mobile-cards">
        <div v-for="order in displayOrders" :key="order.id" class="order-card" @click="router.push(`/orders/${order.id}`)">
          <div class="card-header">
            <div class="order-no-row">
              <span class="order-no-text" :title="order.order_no">{{ shortenOrderNo(order.order_no) }}</span>
              <el-icon class="copy-icon" @click.stop="copyOrderNo(order.order_no)">
                <CopyDocument />
              </el-icon>
            </div>
            <el-tag :type="isRenter(order) ? 'primary' : 'success'" size="small">
              {{ orderRole(order) }}
            </el-tag>
          </div>
          <div class="card-title">{{ order.title }}</div>
          <div class="card-meta">
            <div class="meta-row">
              <span class="meta-label">{{ amountLabel(order) }}</span>
              <span class="meta-value amount">¥{{ money(orderRentAmount(order)) }}</span>
            </div>
            <div v-if="ownerActualIncome(order) !== null" class="meta-row">
              <span class="meta-label">实际到手</span>
              <span class="meta-value amount">¥{{ money(ownerActualIncome(order)) }}</span>
            </div>
            <div class="meta-row">
              <span class="meta-label">押金</span>
              <span class="meta-value">¥{{ money(order.deposit_amount) }}</span>
            </div>
            <div class="meta-row">
              <span class="meta-label">创建时间</span>
              <span class="meta-value">{{ formatDateTime(order.created_at) }}</span>
            </div>
          </div>
          <div class="card-footer">
            <div class="status-info">
              <span class="status-label">{{ orderStatusLabel(order.status) }}</span>
              <span v-if="order.status === 'pending_payment' && getCountdownMinutes(order) > 0" class="countdown-badge">
                {{ getCountdownMinutes(order) }}分钟后超时
              </span>
            </div>
            <el-button
              v-if="order.status === 'pending_payment' && isRenter(order)"
              size="small"
              type="primary"
              :loading="payingOrderId === order.id"
              @click.stop="handlePay(order)"
            >
              立即支付
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<style scoped>
.orders-toolbar {
  margin-top: 24px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  max-width: 400px;
}

.order-tabs {
  margin-top: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #ffffff;
  padding: 0 16px;
}

.order-tabs :deep(.el-tabs__header) {
  margin: 0;
}

.order-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 0;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;
}

.tab-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 20px;
  height: 20px;
  padding: 0 6px;
  border-radius: 10px;
  background: #ff6a00;
  color: #ffffff;
  font-size: 12px;
  font-weight: 600;
}

.order-tabs :deep(.is-active) .tab-count {
  background: #ffffff;
  color: #ff6a00;
}

.orders-container {
  margin-top: 24px;
}

.empty-state {
  margin-top: 60px;
}

.orders-table {
  display: block;
}

.mobile-cards {
  display: none;
}

.order-no-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.order-no-text {
  font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;
  font-size: 13px;
  color: #4a5568;
}

.copy-icon {
  cursor: pointer;
  color: #9ca3af;
  font-size: 14px;
  transition: color 0.2s;
}

.copy-icon:hover {
  color: #ff6a00;
}

.amount-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.amount-value {
  font-weight: 600;
  color: #1f2937;
}

.amount-label {
  font-size: 12px;
  color: #9ca3af;
}

.amount-sub {
  font-size: 12px;
  color: #10b981;
  font-weight: 600;
}

.status-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.countdown-badge {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  background: #fef3c7;
  color: #d97706;
  font-size: 11px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.order-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 16px;
  background: #ffffff;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 12px;
}

.order-card:hover {
  border-color: #ff6a00;
  box-shadow: 0 4px 12px rgba(255, 106, 0, 0.1);
}

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

.order-no-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 12px;
}

.card-meta {
  display: grid;
  gap: 8px;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f3f4f6;
}

.meta-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.meta-label {
  font-size: 13px;
  color: #6b7280;
}

.meta-value {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

.meta-value.amount {
  color: #ff6a00;
  font-weight: 600;
  font-size: 15px;
}

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

.status-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.status-label {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

@media (max-width: 768px) {
  .orders-table {
    display: none;
  }

  .mobile-cards {
    display: block;
  }

  .search-input {
    max-width: 100%;
  }

  .order-tabs {
    padding: 0 8px;
  }

  .order-tabs :deep(.el-tabs__item) {
    padding: 0 12px;
    font-size: 14px;
  }
}
</style>
