<template>
  <view class="page">
    <view class="header-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="top-bar">
        <view class="top-left" @click="goBack">
          <AppIcon name="chevronLeft" size="sm" color="white" />
        </view>
        <view class="top-center">
          <text class="page-title">{{ t('sync.title') }}</text>
          <LocationPicker />
        </view>
        <view class="top-right" @click="isMenuOpen = true">
          <AppIcon name="menu" size="sm" color="white" />
        </view>
      </view>
    </view>

    <view class="content">
      <view class="status-card">
        <view class="status-top">
          <view class="status-icon"><AppIcon :name="syncData.pendingMutations > 0 ? 'refresh' : 'check'" size="lg" color="green" /></view>
          <view>
            <text class="status-title">{{ syncData.pendingMutations > 0 ? t('sync.pendingLocalChanges') : t('sync.allSynced') }}</text>
            <text class="status-time">{{ t('sync.lastSync') }}: {{ syncData.lastSync }} · {{ syncData.online ? t('common.online') : t('common.offline') }}</text>
          </view>
        </view>
        <view class="sync-btn" @click="handleSync">
          <AppIcon name="refresh" size="sm" color="white" />
          <text class="sync-btn-text">{{ t('sync.syncNow') }}</text>
        </view>
      </view>

      <text class="section-title">{{ t('sync.details') }}</text>

      <view class="detail-card">
        <view class="detail-row">
          <view class="detail-left">
            <view class="detail-icon blue"><AppIcon name="cloud" size="md" color="blue" /></view>
            <view>
              <text class="detail-name">{{ t('sync.labels') }}</text>
              <text class="detail-count">{{ syncData.labels.synced }} {{ t('sync.of') }} {{ syncData.labels.total }} {{ t('sync.synced') }}</text>
            </view>
          </view>
          <AppIcon :name="syncData.labels.pending > 0 ? 'refresh' : 'check'" size="md" color="green" />
        </view>
      </view>

      <view class="detail-card">
        <view class="detail-row">
          <view class="detail-left">
            <view class="detail-icon purple"><AppIcon name="cloud" size="md" color="purple" /></view>
            <view>
              <text class="detail-name">{{ t('sync.photos') }}</text>
              <text class="detail-count">{{ syncData.photos.synced }} {{ t('sync.of') }} {{ syncData.photos.total }} {{ t('sync.synced') }}</text>
            </view>
          </view>
          <AppIcon :name="syncData.photos.pending > 0 ? 'refresh' : 'check'" size="md" color="green" />
        </view>
      </view>

      <text class="section-title">{{ t('sync.pendingChanges') }}</text>
      <view class="detail-card">
        <view v-if="pendingList.length === 0" class="pending-empty">
          <text class="pending-empty-text">{{ t('sync.noPendingMutations') }}</text>
        </view>
        <view v-if="pendingList.length > 0" class="pending-tools">
          <view class="pending-tool-btn ghost" @click="handleClearFailed">
            <text class="pending-tool-text">{{ t('sync.clearFailed') }}</text>
          </view>
        </view>
        <view v-if="pendingList.length > 0" class="pending-list">
          <view v-for="row in pendingList" :key="row.id" class="pending-item">
            <view class="pending-main">
              <text class="pending-method">{{ row.method }}</text>
              <text class="pending-endpoint">{{ row.endpoint }}</text>
            </view>
            <text class="pending-time">{{ formatPendingTime(row.createdAt) }}</text>
            <text v-if="row.lastError" class="pending-error">{{ row.lastError }}</text>
            <view class="pending-actions">
              <view class="pending-action-btn primary" @click="handleRetryOne(row.id)">
                <text class="pending-action-text">{{ t('sync.retry') }}</text>
              </view>
              <view class="pending-action-btn danger" @click="handleRemoveOne(row.id)">
                <text class="pending-action-text">{{ t('sync.remove') }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <text class="section-title">{{ t('sync.lastSyncResult') }}</text>
      <view class="detail-card">
        <view class="stat-row">
          <text class="stat-key">{{ t('sync.total') }}</text>
          <text class="stat-val">{{ syncExec.total }}</text>
        </view>
        <view class="stat-row">
          <text class="stat-key">{{ t('sync.success') }}</text>
          <text class="stat-val ok">{{ syncExec.success }}</text>
        </view>
        <view class="stat-row">
          <text class="stat-key">{{ t('sync.failed') }}</text>
          <text class="stat-val bad">{{ syncExec.failed }}</text>
        </view>
        <view class="stat-row">
          <text class="stat-key">{{ t('sync.at') }}</text>
          <text class="stat-val">{{ formatPendingTime(syncExec.at) }}</text>
        </view>
      </view>

      <view class="info-card">
        <text>{{ t('sync.autoSyncInfo') }}</text>
      </view>
    </view>

    <SideMenu v-model="isMenuOpen" />
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { onShow } from '@dcloudio/uni-app'
import AppIcon from '../../components/AppIcon.vue'
import SideMenu from '../../components/SideMenu.vue'
import LocationPicker from '../../components/LocationPicker.vue'
import { getStatusBarHeight } from '../../utils/statusBar'
import {
  clearFailedOfflineMutationItems,
  getOfflineLastSyncExecutionDetail,
  getOfflinePendingMutationPreviewList,
  getOfflineSyncStats,
  removeOfflineMutation,
  retryOfflineMutationById,
  syncNowAndRefreshCaches,
} from '../../utils/offlineSyncManager'
import type { OfflinePendingMutationPreview, OfflineSyncExecutionDetail } from '../../utils/offlineSyncManager'

const { t } = useI18n()
const statusBarHeight = getStatusBarHeight()
const isMenuOpen = ref(false)
const syncData = ref({
  lastSync: '—',
  labels: { total: 0, synced: 0, pending: 0 },
  photos: { total: 0, synced: 0, pending: 0 },
  pendingMutations: 0,
  online: false,
})
const pendingList = ref<OfflinePendingMutationPreview[]>([])
const syncExec = ref<OfflineSyncExecutionDetail>({
  total: 0,
  success: 0,
  failed: 0,
  at: 0,
})

function formatLastSync(ts: number): string {
  if (!ts) return '—'
  const diff = Math.max(0, Math.floor((Date.now() - ts) / 1000))
  if (diff < 60) return t('sync.justNow')
  if (diff < 3600) return t('sync.minutesAgo', { count: Math.floor(diff / 60) })
  if (diff < 86400) return t('sync.hoursAgo', { count: Math.floor(diff / 3600) })
  return t('sync.daysAgo', { count: Math.floor(diff / 86400) })
}

async function refreshStats() {
  try {
    const [s, pending] = await Promise.all([
      getOfflineSyncStats(),
      getOfflinePendingMutationPreviewList(20),
    ])
    syncData.value = {
      lastSync: formatLastSync(s.lastSyncAt),
      labels: s.labels,
      photos: s.photos,
      pendingMutations: s.pendingMutations,
      online: s.online,
    }
    pendingList.value = pending
    syncExec.value = getOfflineLastSyncExecutionDetail()
  } catch {
    // ignore
  }
}

function formatPendingTime(ts: number): string {
  if (!ts) return '—'
  const d = new Date(ts)
  if (!Number.isFinite(d.getTime())) return '—'
  return d.toLocaleString('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.redirectTo({ url: '/pages/index/index' })
  }
}

const handleSync = async () => {
  if (!syncData.value.online) {
    uni.showToast({ title: t('sync.offlineSyncTip'), icon: 'none', duration: 2500 })
    return
  }
  uni.showLoading({ title: t('sync.syncing'), mask: true })
  try {
    await syncNowAndRefreshCaches()
    await refreshStats()
    uni.showToast({ title: t('sync.syncSuccess'), icon: 'success' })
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : String(e)
    uni.showToast({ title: msg || t('sync.syncFailed'), icon: 'none', duration: 2500 })
  } finally {
    uni.hideLoading()
  }
}

const handleRetryOne = async (id: number) => {
  if (!syncData.value.online) {
    uni.showToast({ title: t('sync.offlineSyncTip'), icon: 'none', duration: 2500 })
    return
  }
  uni.showLoading({ title: t('sync.retrying'), mask: true })
  try {
    const r = await retryOfflineMutationById(id)
    if (r.ok) {
      uni.showToast({ title: t('sync.retrySuccess'), icon: 'success' })
    } else {
      uni.showToast({ title: r.message || t('sync.retryFailed'), icon: 'none', duration: 2500 })
    }
    await refreshStats()
  } finally {
    uni.hideLoading()
  }
}

const handleRemoveOne = async (id: number) => {
  await removeOfflineMutation(id)
  uni.showToast({ title: t('sync.removed'), icon: 'success' })
  await refreshStats()
}

const handleClearFailed = async () => {
  const count = await clearFailedOfflineMutationItems()
  uni.showToast({ title: t('sync.clearedItems', { count }), icon: 'success' })
  await refreshStats()
}

onShow(() => {
  refreshStats()
})
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f9fafb;
}

.header-hero {
  background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-dark));
  padding: 16rpx 32rpx 24rpx;
}

.top-bar {
  height: 96rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.top-left,
.top-right {
  width: 64rpx;
  height: 64rpx;
  border-radius: 999rpx;
  background: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
}

.top-center {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #fff;
}

.content {
  padding: 48rpx;
}

.status-card {
  background: #fff;
  padding: 48rpx;
  border-radius: 20rpx;
  margin-bottom: 48rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.status-top {
  display: flex;
  align-items: flex-start;
  gap: 32rpx;
  margin-bottom: 32rpx;
}

.status-icon {
  width: 96rpx;
  height: 96rpx;
  background: #f0fdf4;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.status-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 8rpx;
}

.status-time {
  font-size: 28rpx;
  color: #6b7280;
}

.sync-btn {
  width: 100%;
  height: 96rpx;
  background: var(--theme-primary);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.sync-btn-text {
  font-size: 30rpx;
  font-weight: 600;
  color: #fff;
  line-height: 1;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 24rpx;
}

.detail-card {
  background: #fff;
  padding: 32rpx;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

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

.detail-left {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.detail-icon {
  padding: 16rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-icon.blue {
  background: #eff6ff;
}

.detail-icon.green {
  background: #f0fdf4;
}

.detail-icon.purple {
  background: #faf5ff;
}

.detail-name {
  font-size: 30rpx;
  font-weight: 500;
  color: #111827;
  display: block;
}

.detail-count {
  font-size: 26rpx;
  color: #6b7280;
}

.pending-empty {
  padding: 12rpx 0;
}

.pending-empty-text {
  font-size: 24rpx;
  color: #9ca3af;
}

.pending-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.pending-tools {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12rpx;
}

.pending-tool-btn {
  min-width: 160rpx;
  height: 56rpx;
  padding: 0 16rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pending-tool-btn.ghost {
  background: #eef2ff;
}

.pending-tool-text {
  font-size: 22rpx;
  color: #1e3a8a;
  font-weight: 600;
}

.pending-item {
  border-bottom: 1rpx solid #eef2f7;
  padding-bottom: 16rpx;
}

.pending-item:last-child {
  border-bottom: 0;
  padding-bottom: 0;
}

.pending-main {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.pending-method {
  font-size: 22rpx;
  color: #1e3a8a;
  font-weight: 700;
  min-width: 72rpx;
}

.pending-endpoint {
  font-size: 23rpx;
  color: #1f2937;
  flex: 1;
}

.pending-time {
  margin-top: 6rpx;
  font-size: 22rpx;
  color: #6b7280;
}

.pending-error {
  margin-top: 6rpx;
  font-size: 22rpx;
  color: #b91c1c;
}

.pending-actions {
  margin-top: 10rpx;
  display: flex;
  gap: 12rpx;
}

.pending-action-btn {
  min-width: 120rpx;
  height: 52rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pending-action-btn.primary {
  background: #1e40af;
}

.pending-action-btn.danger {
  background: #b91c1c;
}

.pending-action-text {
  font-size: 22rpx;
  color: #fff;
  font-weight: 600;
}

.stat-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8rpx 0;
  border-bottom: 1rpx solid #eef2f7;
}

.stat-row:last-child {
  border-bottom: 0;
}

.stat-key {
  font-size: 24rpx;
  color: #6b7280;
}

.stat-val {
  font-size: 24rpx;
  color: #111827;
  font-weight: 600;
}

.stat-val.ok {
  color: #15803d;
}

.stat-val.bad {
  color: #b91c1c;
}

.info-card {
  padding: 32rpx;
  background: #eff6ff;
  border: 1rpx solid #bfdbfe;
  border-radius: 16rpx;
  margin-top: 16rpx;
}

.info-card text {
  font-size: 26rpx;
  color: #1e3a8a;
  line-height: 1.5;
}
</style>
