'use client'

import { useState, useEffect } from 'react'
import { Navigation } from '@/components/shared/Navigation'
import './globals.css'
import { SimpleFlipCard } from './components/SimpleFlipCard'
import { SimpleProgress } from './components/SimpleProgress'
import { SimpleResults } from './components/SimpleResults'
import { SIMPLE_CARDS, CardState, sortCardsByPriority, updateCardState } from './data'

export default function SimpleReviewPage() {
  // 延遲計數狀態管理
  const [cards, setCards] = useState<CardState[]>(SIMPLE_CARDS)
  const [score, setScore] = useState({ correct: 0, total: 0 })
  const [isComplete, setIsComplete] = useState(false)

  // 智能排序獲取當前卡片
  const sortedCards = sortCardsByPriority(cards)
  const incompleteCards = sortedCards.filter(card => !card.isCompleted)
  const currentCard = incompleteCards[0] // 總是選擇優先級最高的未完成卡片

  // localStorage進度保存和載入
  useEffect(() => {
    // 載入保存的進度
    const savedProgress = localStorage.getItem('review-progress')
    if (savedProgress) {
      try {
        const parsed = JSON.parse(savedProgress)
        const saveTime = new Date(parsed.timestamp)
        const now = new Date()
        const isToday = saveTime.toDateString() === now.toDateString()

        if (isToday && parsed.cards) {
          setCards(parsed.cards)
          setScore(parsed.score || { correct: 0, total: 0 })
          console.log('📖 載入保存的複習進度')
        }
      } catch (error) {
        console.warn('進度載入失敗:', error)
        localStorage.removeItem('review-progress')
      }
    }
  }, [])

  // 保存進度到localStorage
  const saveProgress = () => {
    const progress = {
      cards,
      score,
      timestamp: new Date().toISOString()
    }
    localStorage.setItem('review-progress', JSON.stringify(progress))
    console.log('💾 進度已保存')
  }

  // 處理答題 - 延遲計數邏輯
  const handleAnswer = (confidence: number) => {
    if (!currentCard) return

    // 信心度2以上算答對 (根據規格修正)
    const isCorrect = confidence >= 2

    // 找到當前卡片在原數組中的索引
    const originalIndex = cards.findIndex(card => card.id === currentCard.id)

    if (isCorrect) {
      // 答對：標記為完成
      const updatedCards = updateCardState(cards, originalIndex, () => ({
        isCompleted: true
      }))
      setCards(updatedCards)
    } else {
      // 答錯：增加答錯次數
      const updatedCards = updateCardState(cards, originalIndex, (card) => ({
        wrongCount: card.wrongCount + 1
      }))
      setCards(updatedCards)
    }

    // 更新分數統計
    setScore(prevScore => ({
      correct: prevScore.correct + (isCorrect ? 1 : 0),
      total: prevScore.total + 1
    }))

    // 保存進度
    saveProgress()

    // 檢查是否完成所有卡片
    const remainingCards = cards.filter(card => !card.isCompleted)
    if (remainingCards.length <= 1) {
      setIsComplete(true)
    }
  }

  // 處理跳過 - 延遲計數邏輯
  const handleSkip = () => {
    if (!currentCard) return

    // 找到當前卡片在原數組中的索引
    const originalIndex = cards.findIndex(card => card.id === currentCard.id)

    // 增加跳過次數
    const updatedCards = updateCardState(cards, originalIndex, (card) => ({
      skipCount: card.skipCount + 1
    }))
    setCards(updatedCards)

    // 保存進度
    saveProgress()

    // 檢查是否完成所有卡片
    const remainingCards = updatedCards.filter(card => !card.isCompleted)
    if (remainingCards.length === 0) {
      setIsComplete(true)
    }
  }

  // 重新開始 - 重置所有狀態
  const handleRestart = () => {
    setCards(SIMPLE_CARDS) // 重置為初始狀態
    setScore({ correct: 0, total: 0 })
    setIsComplete(false)
    localStorage.removeItem('review-progress') // 清除保存的進度
    console.log('🔄 複習進度已重置')
  }

  // 顯示結果頁面
  if (isComplete) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
        <Navigation />
        <div className="py-8">
          <SimpleResults
            score={score}
            totalCards={SIMPLE_CARDS.length}
            onRestart={handleRestart}
          />
        </div>
      </div>
    )
  }

  // 主要複習頁面
  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      <Navigation />

      <div className="py-8">
        <div className="max-w-4xl mx-auto px-4">
          {/* 進度顯示 */}
          <SimpleProgress
            current={cards.filter(card => card.isCompleted).length + 1}
            total={cards.length}
            score={score}
            cards={cards}
          />

          {/* 翻卡組件 */}
          {currentCard && (
            <SimpleFlipCard
              card={currentCard}
              onAnswer={handleAnswer}
              onSkip={handleSkip}
            />
          )}

        </div>
      </div>
    </div>
  )
}