import React, { useEffect, useMemo } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import {
  Box,
  Button,
  Heading,
  Text,
  VStack,
} from '@chakra-ui/react'

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

export const CompletedPage = () => {
  const navigate = useNavigate()
  const { chainId } = useParams<{ chainId: string }>()
  const { nickname, chains } = useChallenge()

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

  const chain = useMemo(() => {
    return chains.find(c => c.id === chainId) || null
  }, [chains, chainId])

  const handleContinue = () => {
    navigate(URLs.chains)
  }

  if (!nickname) {
    return null
  }

  return (
    <>
      <Header />
      <Box bg="gray.50" minH="100vh" display="flex" alignItems="center" justifyContent="center" px={4}>
        <Box
          bg="white"
          borderWidth="2px"
          borderRadius="xl"
          borderColor="green.300"
          p={10}
          maxW="600px"
          w="full"
          textAlign="center"
          shadow="lg"
        >
          <VStack gap={6}>
            <Text fontSize="6xl">🎉</Text>
            <Heading size="xl" color="green.600">
              Поздравляем!
            </Heading>
            <Text fontSize="lg" color="gray.700">
              Вы успешно выполнили все задания
            </Text>
            {chain && (
              <Box 
                bg="green.50" 
                borderRadius="lg" 
                px={6} 
                py={3}
                borderWidth="1px"
                borderColor="green.200"
              >
                <Text fontSize="xl" fontWeight="bold" color="green.700">
                  {chain.name}
                </Text>
              </Box>
            )}
            <Text fontSize="md" color="gray.600">
              Отличная работа! Вы можете продолжить обучение, выбрав другую цепочку заданий.
            </Text>
            <Button
              colorScheme="green"
              size="lg"
              onClick={handleContinue}
              mt={4}
            >
              Продолжить
            </Button>
          </VStack>
        </Box>
      </Box>
    </>
  )
}

