import React, { useEffect, useRef, useMemo } from 'react'
import { useParams, Link } from 'react-router-dom'
import dayjs from 'dayjs'
import QRCode from 'qrcode'
import { sha256 } from 'js-sha256'
import { getConfigValue, getNavigationValue } from '@brojs/cli'
import {
  Box,
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  Container,
  VStack,
  Heading,
  Stack,
} from '@chakra-ui/react'
import { useTranslation } from 'react-i18next'

import { api } from '../__data__/api/api'
import { User } from '../__data__/model'
import { UserCard } from '../components/user-card'

import {
  QRCanvas,
  StudentList,
  BreadcrumbsWrapper,
} from './style'
import { useAppSelector } from '../__data__/store'
import { isTeacher } from '../utils/user'

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 canvRef = useRef(null)
  const user = useAppSelector((s) => s.user)
  const { t } = useTranslation()
  
  const {
    isFetching,
    data: accessCode,
    isSuccess,
    refetch,
  } = api.useCreateAccessCodeQuery(
    { lessonId },
    {
      skip: !isTeacher(user),
      pollingInterval:
        Number(getConfigValue('journal.polling-interval')) || 3000,
      skipPollingIfUnfocused: true,
    },
  )
  const AllStudents = api.useCourseAllStudentsQuery(courseId)
  const [manualAdd, manualAddRqst] = api.useManualAddStudentMutation()
  const userUrl = useMemo(
    () => `${location.origin}/journal/u/${lessonId}/${accessCode?.body?._id}`,
    [accessCode, lessonId],
  )

  useEffect(() => {
    if (manualAddRqst.isSuccess) {
      refetch()
    }
  }, [manualAddRqst.isSuccess])

  useEffect(() => {
    if (!isFetching && isSuccess) {
      const generateQRCode = () => {
        if (!canvRef.current) return;
        
        // Получаем текущую ширину канваса, гарантируя квадратный QR-код
        const canvas = canvRef.current;
        const containerWidth = canvas.clientWidth;
        
        // Очищаем canvas перед новой генерацией
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // Устанавливаем одинаковые размеры для ширины и высоты (1:1)
        canvas.width = containerWidth;
        canvas.height = containerWidth;
        
        QRCode.toCanvas(
          canvas,
          userUrl,
          { 
            width: containerWidth,
            margin: 1 // Небольшой отступ для лучшей читаемости
          },
          function (error) {
            if (error) console.error(error)
            console.log('success!')
          },
        )
      }
      
      // Генерируем QR-код
      generateQRCode();
      
      // Перегенерируем при изменении размера окна
      const handleResize = () => {
        generateQRCode();
      };
      
      window.addEventListener('resize', handleResize);
      
      return () => {
        window.removeEventListener('resize', handleResize);
      };
    }
  }, [isFetching, isSuccess, userUrl])

  const studentsArr = useMemo(() => {
    let allStudents: (User & { present?: boolean })[] = [
      ...(AllStudents.data?.body || []),
    ].map((st) => ({ ...st, present: false }))
    let presentStudents: (User & { present?: boolean })[] = [
      ...(accessCode?.body.lesson.students || []),
    ]

    while (presentStudents.length) {
      const student = presentStudents.pop()

      const present = allStudents.find((st) => st.sub === student.sub)

      if (present) {
        present.present = true
      } else {
        allStudents.push({ ...student, present: true })
      }
    }

    return allStudents.sort((a, b) => (a.present ? -1 : 1))
  }, [accessCode?.body, AllStudents.data])

  return (
    <>
      <BreadcrumbsWrapper>
        <Breadcrumb>
          <BreadcrumbItem>
            <BreadcrumbLink as={Link} to={getNavigationValue('journal.main')}>
              {t('journal.pl.common.journal')}
            </BreadcrumbLink>
          </BreadcrumbItem>

          <BreadcrumbItem>
            <BreadcrumbLink
              as={Link}
              to={`${getNavigationValue('journal.main')}/lessons-list/${courseId}`}
            >
              {t('journal.pl.common.course')}
            </BreadcrumbLink>
          </BreadcrumbItem>

          <BreadcrumbItem isCurrentPage>
            <BreadcrumbLink href="#">{t('journal.pl.common.lesson')}</BreadcrumbLink>
          </BreadcrumbItem>
        </Breadcrumb>
      </BreadcrumbsWrapper>
      <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>
          <Box as="span">
            {dayjs(accessCode?.body?.lesson?.date).format(t('journal.pl.lesson.dateFormat'))}{' '}
            {t('journal.pl.common.marked')} - {accessCode?.body?.lesson?.students?.length}{' '}
            {AllStudents.isSuccess
              ? `/ ${AllStudents?.data?.body?.length}`
              : ''}{' '}
            {t('journal.pl.common.people')}
          </Box>
        </VStack>
        <Stack spacing="8" direction={{ base: "column", md: "row" }}>
          <Box flexShrink={0} alignSelf="center">
            <a href={userUrl}>
              <QRCanvas ref={canvRef} />
            </a>
          </Box>
          <StudentList>
            {isTeacher(user) && studentsArr.map((student) => (
              <UserCard
                wrapperAS="li"
                key={student.sub}
                student={student}
                present={student.present}
                onAddUser={(user: User) => manualAdd({ lessonId, user })}
              />
            ))}
          </StudentList>
        </Stack>
      </Container>
    </>
  )
}

export default LessonDetail
