/**
 * 阅卷导航管理
 * 移动端版本 - 支持手势操作
 */
import type { Ref } from 'vue'
import { injectLocal, provideLocal } from '@vueuse/core'
import { computed } from 'vue'
import { useMarkingHistory } from './useMarkingHistory'

interface MarkingNavigationProps {
  taskId: Ref<number>
}

/**
 * 手势方向枚举
 */
export enum SwipeDirection {
  Left = 'left',
  Right = 'right',
  Up = 'up',
  Down = 'down',
}

function createMarkingNavigation(_props: MarkingNavigationProps) {
  // 获取历史记录管理
  const {
    totalHistoryCount,
    currentHistoryIndex,
    isViewingHistory,
    currentHistoryRecord,
    canGoPrev,
    canGoNext,
    progressInfo,
    goToHistoryIndex,
    goToPrevHistory,
    goToNextHistory,
    switchToHistoryMode,
    switchToCurrentMode,
  } = useMarkingHistory()

  // ==================== 导航状态 ====================

  // 当前索引（历史查看时显示历史序号，否则显示当前进度）
  const currentIndex = computed(() => {
    return progressInfo.value.current
  })

  // 总数
  const totalCount = computed(() => {
    return progressInfo.value.total
  })

  // 当前进度百分比
  const progressPercentage = computed(() => {
    return progressInfo.value.percentage
  })

  // 历史记录题目信息
  const currentHistoryQuestionInfo = computed(() => {
    if (!isViewingHistory.value || !currentHistoryRecord.value) {
      return null
    }

    const record = currentHistoryRecord.value
    return {
      questionId: record.question_id || 0,
      taskId: record.task_id || 0,
      recordId: record.id || 0,
      sequence: currentHistoryIndex.value + 1,
      score: record.score || 0,
      createdTime: record.created_time || '',
      isExcellent: record.is_excellent === 1,
      isModel: record.is_model === 1,
      isProblem: record.is_problem === 1,
    }
  })

  // ==================== 导航方法 ====================

  /**
   * 上一题
   */
  const goToPrevQuestion = async () => {
    console.log('🤚 上一题', {
      canGoPrev: canGoPrev.value,
      isViewingHistory: isViewingHistory.value,
      totalHistoryCount: totalHistoryCount.value,
    })
    if (canGoPrev.value) {
      return await goToPrevHistory()
    }

    // 如果当前不在历史模式，且有历史记录，则进入历史模式查看最新记录
    if (!isViewingHistory.value && totalHistoryCount.value > 0) {
      return await goToHistoryIndex(totalHistoryCount.value - 1)
    }

    return false
  }

  /**
   * 下一题
   */
  const goToNextQuestion = async () => {
    if (canGoNext.value) {
      return await goToNextHistory()
    }

    // 如果是历史记录的最后一题，则跳转到当前阅卷
    if (isViewingHistory.value && currentHistoryIndex.value === totalHistoryCount.value - 1) {
      switchToCurrentMode()
      return true
    }

    return false
  }

  // ==================== 手势支持 ====================

  /**
   * 手势配置
   */
  const swipeConfig = {
    threshold: 40, // 最小滑动距离（px）
    timeout: 200, // 最大滑动时间（ms）
  }

  /**
   * 处理滑动手势
   */
  const handleSwipe = async (direction: SwipeDirection): Promise<boolean> => {
    console.log('🤚 检测到滑动手势:', direction)

    switch (direction) {
      case SwipeDirection.Left:
        // 左滑：下一题
        return await goToNextQuestion()

      case SwipeDirection.Right:
        // 右滑：上一题
        return await goToPrevQuestion()

      default:
        return false
    }
  }

  /**
   * 创建手势处理器
   * 返回触摸事件处理函数
   */
  const createSwipeHandler = () => {
    let startX = 0
    let startY = 0
    let startTime = 0

    const onTouchStart = (event: TouchEvent) => {
      const touch = event.touches[0]
      startX = touch.clientX
      startY = touch.clientY
      startTime = Date.now()
    }

    const onTouchEnd = async (event: TouchEvent) => {
      const touch = event.changedTouches[0]
      const endX = touch.clientX
      const endY = touch.clientY
      const endTime = Date.now()

      const deltaX = endX - startX
      const deltaY = endY - startY
      const deltaTime = endTime - startTime

      // 检查是否超时
      if (deltaTime > swipeConfig.timeout) {
        return
      }

      // 计算滑动距离
      const absX = Math.abs(deltaX)
      const absY = Math.abs(deltaY)

      // 检查是否达到阈值
      if (absX < swipeConfig.threshold && absY < swipeConfig.threshold) {
        return
      }

      // 判断滑动方向（优先水平方向）
      if (absX > absY) {
        // 水平滑动
        if (deltaX > 0) {
          await handleSwipe(SwipeDirection.Right)
        }
        else {
          await handleSwipe(SwipeDirection.Left)
        }
      }
      else {
        // 垂直滑动
        if (deltaY > 0) {
          await handleSwipe(SwipeDirection.Down)
        }
        else {
          await handleSwipe(SwipeDirection.Up)
        }
      }
    }

    return {
      onTouchStart,
      onTouchEnd,
    }
  }

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

  /**
   * 初始化导航状态
   */
  const initNavigation = async () => {
    console.log('🚀 初始化导航状态')
    // 默认切换到当前阅卷模式
    switchToCurrentMode()
  }

  return {
    // 基础状态
    currentIndex,
    totalCount,
    currentHistoryIndex,
    isViewingHistory: readonly(isViewingHistory),
    currentHistoryQuestionInfo,
    currentHistoryQuestion: currentHistoryRecord,
    totalHistoryCount,

    // 计算属性
    canGoPrev: computed(
      () => canGoPrev.value || (!isViewingHistory.value && totalHistoryCount.value > 0),
    ),
    canGoNext: computed(
      () =>
        canGoNext.value
        || (currentHistoryIndex.value === totalHistoryCount.value - 1 && isViewingHistory.value),
    ),
    progressPercentage,

    // 导航方法
    initNavigation,
    goToPrevQuestion,
    goToNextQuestion,
    goToHistoryIndex,

    // 模式切换
    switchToHistoryMode,
    switchToCurrentMode,

    // 手势支持
    handleSwipe,
    createSwipeHandler,
    swipeConfig,
  }
}

export type MarkingNavigation = ReturnType<typeof createMarkingNavigation>
const MarkingNavigationSymbol = Symbol('MarkingNavigation')

export function provideMarkingNavigation(props: MarkingNavigationProps) {
  const markingNavigation = createMarkingNavigation(props)
  provideLocal(MarkingNavigationSymbol, markingNavigation)
  return markingNavigation
}

export function useMarkingNavigation() {
  const markingNavigation = injectLocal<MarkingNavigation>(MarkingNavigationSymbol)
  if (!markingNavigation) {
    throw new Error('MarkingNavigation not found. Make sure to call provideMarkingNavigation first.')
  }
  return markingNavigation
}
