import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

import { URLs } from '../../__data__/urls'
import { useChallenge } from '../../context/ChallengeContext'
import { Header } from '../../components/Header'
import { ChainSelector } from '../../components/ChainSelector'
import { storage } from '../../utils/storage'
import type { ChallengeChain } from '../../__data__/types'

export const ChainsPage = () => {
  const navigate = useNavigate()
  const { nickname } = useChallenge()

  // Проверяем авторизацию
  useEffect(() => {
    const workplaceNumber = storage.getWorkplaceNumber()
    if (!workplaceNumber) {
      navigate(URLs.workplace, { replace: true })
      return
    }
    if (!nickname) {
      navigate(URLs.login, { replace: true })
    }
  }, [navigate, nickname])

  const handleSelectChain = (chain: ChallengeChain) => {
    storage.setSelectedChainId(chain.id)
    
    if (chain.tasks.length > 0) {
      // Получаем самый дальний достигнутый индекс
      const furthestIndex = storage.getFurthestTaskIndex(chain.id)
      
      // Если нет прогресса, инициализируем с первого задания
      const targetIndex = furthestIndex >= 0 ? furthestIndex : 0
      const targetTask = chain.tasks[targetIndex] || chain.tasks[0]
      
      storage.setSelectedTaskId(targetTask.id)
      // Убеждаемся, что прогресс установлен
      storage.setFurthestTaskIndex(chain.id, targetIndex)
      
      navigate(URLs.task(chain.id, targetTask.id))
    }
  }

  if (!nickname) {
    return null
  }

  return (
    <>
      <Header />
      <ChainSelector onSelectChain={handleSelectChain} />
    </>
  )
}

