import React from 'react'
import { useParams } from 'react-router-dom'

import { api } from '../__data__/api/api'
import dayjs from 'dayjs'
import {
  Alert,
  AlertIcon,
  Box,
  Center,
  Container,
  Heading,
  Spinner,
  Text,
  Stack,
} from '@chakra-ui/react'
import { UserCard } from '../components/user-card'

const UserPage = () => {
  const { lessonId, accessId } = useParams()
  const acc = api.useGetAccessQuery({ accessCode: accessId })

  const ls = api.useLessonByIdQuery(lessonId, {
    pollingInterval: 1000,
    skipPollingIfUnfocused: true,
  })

  if (acc.isLoading) {
    return (
      <Container maxW="container.xl">
        <Center h="300px">
          <Spinner
            thickness="4px"
            speed="0.65s"
            emptyColor="gray.200"
            color="blue.500"
            size="xl"
          />
        </Center>
      </Container>
    )
  }

  return (
    <Container>
      {acc.isLoading && <h1>Отправляем запрос</h1>}
      {acc.isSuccess && <h1>Успешно</h1>}

      {acc.error && (
        <Box mb="6" mt="2">
          <Alert status="warning">
            <AlertIcon />
            {(acc as any).error?.data?.body?.errorMessage ===
            'Code is expired' ? (
              'Не удалось активировать код доступа. Попробуйте отсканировать код ещё раз'
            ) : (
              <pre>{JSON.stringify(acc.error, null, 4)}</pre>
            )}
          </Alert>
        </Box>
      )}

      <Box mb={6}>
        <Text fontSize={18} fontWeight={600} as="h1" mt="4" mb="3">
          Тема занятия: {ls.data?.body?.name}
        </Text>

        <span>{dayjs(ls.data?.body?.date).format('DD MMMM YYYYг.')}</span>
      </Box>

      <Box
        as="ul"
        display="flex"
        flexWrap="wrap"
        justifyContent="center"
        gap={3}
      >
        {ls.data?.body?.students?.map((student) => (
          <UserCard
            width="40%"
            wrapperAS="li"
            key={student.sub}
            student={student}
            present
          />
        ))}
      </Box>
    </Container>
  )
}

export default UserPage
