/**
 * 阅卷历史记录管理
 * 移动端优化版本 - 简化分页逻辑，使用 TanStack Query
 */
import type { Ref } from 'vue'
import type { MarkingHistoryRecord } from './MarkingContext'
import { useQuery, useQueryClient } from '@tanstack/vue-query'
import { injectLocal, provideLocal, useDebounceFn } from '@vueuse/core'
import { computed, readonly, ref, watch } from 'vue'
import { getMarkingContext } from './MarkingContext'

export interface MarkingHistoryProps {
  taskId: Ref<number>
}

// 统一的分页大小常量
const PAGE_SIZE = 20

/**
 * 阅卷历史记录管理
 *
 * 优化要点：
 * 1. 简化索引映射：直接使用从旧到新的索引（0 = 最旧，n-1 = 最新）
 * 2. 按需加载：只在需要时加载对应页面
 * 3. 智能缓存：使用 TanStack Query 自动管理缓存
 */
function createMarkingHistory({ taskId }: MarkingHistoryProps) {
  console.log('createMarkingHistory', taskId)

  const queryClient = useQueryClient()

  // 获取阅卷上下文
  const markingContext = getMarkingContext()

  // ==================== 状态管理 ====================

  // 历史记录总数
  const totalHistoryCount = ref(0)
  // 来自历史记录的总分
  const historyTotalScore = ref(0)

  // 当前查看的历史记录索引（从0开始，0=最旧，n-1=最新）
  const currentHistoryIndex = ref(-1)

  // 是否处于历史查看模式
  const isViewingHistory = ref(false)

  // ==================== 数据获取 ====================

  /**
   * 根据全局索引计算页码和页内索引
   *
   * 简化版本：
   * - 索引 0-19 在第1页
   * - 索引 20-39 在第2页
   * - 以此类推
   *
   * 但后端返回是倒序（最新的在前），所以需要反转
   * 例如：总共25条
   * - 索引0（最旧）对应第3页的最后一条
   * - 索引24（最新）对应第1页的第一条
   */
  const getPageInfoByIndex = (index: number) => {
    const total = totalHistoryCount.value
    if (total === 0 || index < 0 || index >= total) {
      return { page: 1, indexInPage: 0 }
    }

    // 反转索引：将"从旧到新"转换为"从新到旧"
    const reverseIndex = total - 1 - index

    // 计算页码和页内索引
    const page = Math.floor(reverseIndex / PAGE_SIZE) + 1
    const indexInPage = reverseIndex % PAGE_SIZE

    return { page, indexInPage }
  }

  /**
   * 获取历史记录分页数据
   */
  const useHistoryPage = (page: Ref<number>) => {
    return useQuery({
      queryKey: computed(() => ['marking-history', taskId.value, toValue(page)]),
      queryFn: async () => {
        const currentPage = toValue(page)
        console.log(`📚 获取历史记录第 ${currentPage} 页`)

        const response = await markingContext.historyProvider.getHistoryPage(taskId.value, {
          page: currentPage,
          page_size: PAGE_SIZE,
        })

        return {
          list: response?.list || [],
          page: response?.page || currentPage,
          pageSize: response?.page_size || PAGE_SIZE,
          total: response?.total || 0,
          hasMore: response?.has_more || false,
        }
      },
      select(data) {
        // 第一页时更新总数
        if (page.value === 1) {
          totalHistoryCount.value = data.total
          // 获取总分（从第一条记录）
          if (data.list.length > 0) {
            historyTotalScore.value = data.list[0].full_score || 0
          }
        }
        return data
      },
      enabled: computed(() => !!taskId.value),
      staleTime: 5 * 60 * 1000, // 5分钟内认为数据是新鲜的
      gcTime: 10 * 60 * 1000, // 10分钟后清理缓存
    })
  }

  /**
   * 获取当前查看的历史记录详情
   */
  const currentHistoryRecord = computed(() => {
    if (!isViewingHistory.value || currentHistoryIndex.value < 0) {
      return null
    }

    const { page, indexInPage } = getPageInfoByIndex(currentHistoryIndex.value)
    const pageData = queryClient.getQueryData([
      'marking-history',
      taskId.value,
      page,
    ]) as any

    return (pageData?.list?.[indexInPage] as MarkingHistoryRecord) || null
  })

  // ==================== 导航控制 ====================

  /**
   * 预加载指定索引的历史记录
   */
  const preloadHistoryRecord = async (
    index: number,
  ): Promise<MarkingHistoryRecord | null> => {
    if (index < 0 || index >= totalHistoryCount.value) {
      return null
    }

    const { page, indexInPage } = getPageInfoByIndex(index)

    // 检查是否已缓存
    let pageData = queryClient.getQueryData([
      'marking-history',
      taskId.value,
      page,
    ]) as any

    if (!pageData) {
      console.log(`📥 预加载历史记录第 ${page} 页`)
      // 手动触发查询
      await queryClient.fetchQuery({
        queryKey: ['marking-history', taskId.value, page],
        queryFn: async () => {
          return await markingContext.historyProvider.getHistoryPage(taskId.value, {
            page,
            page_size: PAGE_SIZE,
          })
        },
        staleTime: 5 * 60 * 1000,
        gcTime: 10 * 60 * 1000,
      })

      pageData = queryClient.getQueryData(['marking-history', taskId.value, page]) as any
    }

    return pageData?.list?.[indexInPage] || null
  }

  /**
   * 跳转到指定索引的历史记录
   */
  const goToHistoryIndex = async (index: number): Promise<boolean> => {
    if (index < 0 || index >= totalHistoryCount.value) {
      console.warn(`⚠️ 历史记录索引超出范围: ${index}, 总数: ${totalHistoryCount.value}`)
      return false
    }

    const { page, indexInPage } = getPageInfoByIndex(index)
    console.log(
      `🎯 跳转到历史记录 - 全局索引: ${index + 1}/${totalHistoryCount.value}, `
      + `页码: ${page}, 页内索引: ${indexInPage}`,
    )

    try {
      // 预加载目标记录
      const record = await preloadHistoryRecord(index)
      if (!record) {
        console.error(`❌ 无法加载历史记录索引: ${index}`)
        return false
      }

      // 更新状态
      currentHistoryIndex.value = index
      isViewingHistory.value = true

      console.log(
        `✅ 成功跳转到历史记录: ${record.question_major}-${record.question_minor}, `
        + `ID: ${record.id}`,
      )
      return true
    }
    catch (error) {
      console.error(`❌ 跳转历史记录失败:`, error)
      return false
    }
  }

  /**
   * 上一条历史记录
   */
  const goToPrevHistory = async (): Promise<boolean> => {
    if (currentHistoryIndex.value <= 0) {
      return false
    }
    return await goToHistoryIndex(currentHistoryIndex.value - 1)
  }

  /**
   * 下一条历史记录
   */
  const goToNextHistory = async (): Promise<boolean> => {
    if (currentHistoryIndex.value >= totalHistoryCount.value - 1) {
      return false
    }
    return await goToHistoryIndex(currentHistoryIndex.value + 1)
  }

  /**
   * 退出历史查看模式
   */
  const exitHistoryMode = () => {
    console.log('🚪 退出历史查看模式')
    isViewingHistory.value = false
    currentHistoryIndex.value = -1
  }

  // ==================== 数据更新 ====================

  /**
   * 强制刷新历史记录（清除所有缓存并重新获取）
   */
  const forceRefreshHistory = async () => {
    console.log('🔄 强制刷新历史记录')

    // 清除所有相关的查询缓存
    queryClient.removeQueries({ queryKey: ['marking-history', taskId.value] })

    // 重置状态
    totalHistoryCount.value = 0
    currentHistoryIndex.value = -1
    isViewingHistory.value = false

    // 重新初始化
    // eslint-disable-next-line ts/no-use-before-define
    await initHistory()

    console.log('✅ 历史记录强制刷新完成')
  }

  /**
   * 提交新记录后更新总数
   */
  const incrementHistoryCount = (count = 1) => {
    const oldTotal = totalHistoryCount.value
    console.log(`➕ 增加历史记录总数: +${count}，从 ${oldTotal} 到 ${oldTotal + count}`)

    totalHistoryCount.value += count

    // 新记录会插入到后端第1页的开头，清理所有缓存
    console.log('🗑️ 清理所有历史记录缓存')
    queryClient.removeQueries({ queryKey: ['marking-history', taskId.value] })

    console.log(`✅ 历史记录总数已更新为: ${totalHistoryCount.value}`)
  }

  // ==================== 计算属性 ====================

  // 是否可以上一条
  const canGoPrev = computed(() => {
    return isViewingHistory.value && currentHistoryIndex.value > 0
  })

  // 是否可以下一条
  const canGoNext = computed(() => {
    return isViewingHistory.value && currentHistoryIndex.value < totalHistoryCount.value - 1
  })

  // 当前进度信息
  const progressInfo = computed(() => {
    if (!isViewingHistory.value) {
      return {
        current: totalHistoryCount.value + 1,
        total: totalHistoryCount.value + 1,
        percentage: 100,
      }
    }

    const current = currentHistoryIndex.value + 1
    return {
      current,
      total: totalHistoryCount.value,
      percentage:
        totalHistoryCount.value > 0 ? Math.round((current / totalHistoryCount.value) * 100) : 0,
    }
  })

  // ==================== 模式切换 ====================

  /**
   * 切换到历史查看模式
   */
  const switchToHistoryMode = async () => {
    console.log('🔄 切换到历史查看模式')

    if (totalHistoryCount.value > 0) {
      const context = markingContext
      const defaultPosition = context.defaultPosition || 'last'

      if (defaultPosition === 'first') {
        await goToHistoryIndex(0)
      }
      else {
        await goToHistoryIndex(totalHistoryCount.value - 1)
      }
    }
  }

  /**
   * 切换到当前阅卷模式
   */
  const switchToCurrentMode = () => {
    console.log('🔄 切换到当前阅卷模式')
    exitHistoryMode()
  }

  // ==================== 初始化 ====================

  /**
   * 初始化历史记录（获取总数）
   */
  const initHistory = useDebounceFn(async () => {
    console.log('🚀 初始化历史记录管理')

    if (!taskId.value) {
      console.warn('⚠️ taskId 为空，跳过历史记录初始化')
      return
    }

    try {
      // 获取第一页数据来获取总数
      const response = await queryClient.fetchQuery({
        queryKey: ['marking-history', taskId.value, 1],
        queryFn: async () => {
          const response = await markingContext.historyProvider.getHistoryPage(taskId.value, {
            page: 1,
            page_size: PAGE_SIZE,
          })
          return response
        },
        staleTime: 5 * 60 * 1000,
        gcTime: 10 * 60 * 1000,
      })

      historyTotalScore.value = response?.list?.[0]?.full_score || 0
      totalHistoryCount.value = response?.total || 0

      console.log(`✅ 历史记录初始化完成，总数: ${totalHistoryCount.value}`)
    }
    catch (error) {
      console.error('❌ 历史记录初始化失败:', error)
      totalHistoryCount.value = 0
    }
  }, 100)

  // 监听 taskId 变化，重新初始化
  watch(
    taskId,
    async (newTaskId, oldTaskId) => {
      if (newTaskId && newTaskId !== oldTaskId) {
        // 重置状态
        totalHistoryCount.value = 0
        currentHistoryIndex.value = -1
        isViewingHistory.value = false

        // 重新初始化
        await initHistory()
      }
    },
    { immediate: true },
  )

  return {
    // 状态
    totalHistoryCount: readonly(totalHistoryCount),
    currentHistoryIndex: readonly(currentHistoryIndex),
    isViewingHistory: readonly(isViewingHistory),
    historyTotalScore: readonly(historyTotalScore),
    currentHistoryRecord,

    // 计算属性
    canGoPrev,
    canGoNext,
    progressInfo,

    // 导航方法
    goToHistoryIndex,
    goToPrevHistory,
    goToNextHistory,
    exitHistoryMode,

    // 模式切换
    switchToHistoryMode,
    switchToCurrentMode,

    // 数据管理
    incrementHistoryCount,
    forceRefreshHistory,
    preloadHistoryRecord,

    // 初始化
    initHistory,

    // 工具方法
    useHistoryPage,
  }
}

type MarkingHistory = ReturnType<typeof createMarkingHistory>
const MarkingHistorySymbol = Symbol('MarkingHistory')

export function provideMarkingHistory(props: MarkingHistoryProps) {
  const markingHistory = createMarkingHistory(props)
  provideLocal(MarkingHistorySymbol, markingHistory)
  return markingHistory
}

export function useMarkingHistory() {
  const markingHistory = injectLocal<MarkingHistory>(MarkingHistorySymbol)
  if (!markingHistory) {
    throw new Error('MarkingHistory not found. Make sure to call provideMarkingHistory first.')
  }
  return markingHistory
}
