import React, { useMemo } from 'react'
import { useParams } from 'react-router-dom'
import { sha256 } from 'js-sha256'
import { getNavigationValue } from '@brojs/cli'
import {
  Box,
  Container,
  VStack,
  Heading,
  Stack,
  useColorMode,
} from '@chakra-ui/react'
import { useTranslation } from 'react-i18next'

import { api } from '../__data__/api/api'
import { useSetBreadcrumbs } from '../components'
import { useAppSelector } from '../__data__/store'
import { isTeacher } from '../utils/user'

// Custom hooks
import { useAccessCode } from '../hooks/useAccessCode'
import { useStudentAttendance } from '../hooks/useStudentAttendance'
import { useStudentReactions } from '../hooks/useStudentReactions'

// Components
import { QRCodeDisplay } from '../components/lesson/QRCodeDisplay'
import { AttendanceStats } from '../components/lesson/AttendanceStats'
import { StudentList } from '../components/lesson/StudentList'

export function getGravatarURL(email, user) {
  if (!email) return void 0
  const address = String(email).trim().toLowerCase()
  const hash = sha256(address)

  // Grab the actual image URL
  return `https://www.gravatar.com/avatar/${hash}?d=robohash`
}

const LessonDetail = () => {
  const { lessonId, courseId } = useParams()
  const user = useAppSelector((s) => s.user)
  const { t } = useTranslation()
  const { colorMode } = useColorMode()
  
  // Получаем данные о курсе и уроке
  const { data: courseData } = api.useGetCourseByIdQuery(courseId)
  const { data: lessonData } = api.useLessonByIdQuery(lessonId)
  
  // Устанавливаем хлебные крошки
  useSetBreadcrumbs([
    {
      title: t('journal.pl.breadcrumbs.home'),
      path: '/'
    },
    {
      title: courseData?.name || t('journal.pl.breadcrumbs.course'),
      path: `${getNavigationValue('journal.main')}/lessons-list/${courseId}`
    },
    {
      title: lessonData?.body?.name || t('journal.pl.breadcrumbs.lesson'),
      isCurrentPage: true
    }
  ])
  
  // Используем кастомные хуки
  const {
    isFetching,
    accessCode,
    isSuccess,
    handleManualAdd
  } = useAccessCode(lessonId, user)
  
  const AllStudents = api.useCourseAllStudentsQuery(courseId)
  
  const { studentsArr, isPulsing } = useStudentAttendance(accessCode, AllStudents)
  const { studentReactions } = useStudentReactions(accessCode)
  
  // Создаем URL для QR-кода
  const userUrl = useMemo(
    () => `${location.origin}/journal/u/${lessonId}/${accessCode?.body?._id}`,
    [accessCode, lessonId],
  )

  return (
    <>
      <Container maxW="2280px">
        <VStack align="left">
          <Heading as="h3" mt="4" mb="3">
            {t('journal.pl.lesson.topicTitle')}
          </Heading>
          <Box as="span">{accessCode?.body?.lesson?.name}</Box>
        </VStack>
        <Stack spacing="8" direction={{ base: "column", md: "row" }} mt={6}>
          <Box 
            flexShrink={0} 
            alignSelf="flex-start" 
            p={4} 
            borderRadius="xl" 
            bg={colorMode === "light" ? "gray.50" : "gray.700"}
            boxShadow="md"
            position="sticky"
            top="20px"
            zIndex="2"
          >
            <AttendanceStats
              lessonDate={accessCode?.body?.lesson?.date}
              studentsPresent={accessCode?.body?.lesson?.students?.length || 0}
              totalStudents={AllStudents?.data?.body?.length || 0}
              isLoading={!AllStudents.isSuccess}
              isPulsing={isPulsing}
            />
            <QRCodeDisplay 
              url={userUrl} 
              isFetching={isFetching} 
              isSuccess={isSuccess} 
            />
          </Box>
          <Box 
            flex={1} 
            p={4} 
            borderRadius="xl" 
            bg={colorMode === "light" ? "gray.50" : "gray.700"}
            boxShadow="md"
          >
            {isTeacher(user) && (
              <StudentList 
                students={studentsArr}
                onAddUser={handleManualAdd}
                studentReactions={studentReactions}
              />
            )}
          </Box>
        </Stack>
      </Container>
    </>
  )
}

export default LessonDetail
