import React, { useCallback, useEffect, useState } from 'react'
import dayjs from 'dayjs'
import { Link as ConnectedLink, generatePath } from 'react-router-dom'
import { getNavigationsValue } from '@brojs/cli'
import {
  Box,
  CardHeader,
  CardBody,
  CardFooter,
  ButtonGroup,
  Stack,
  StackDivider,
  Button,
  Card,
  Heading,
  Tooltip,
  Spinner,
} from '@chakra-ui/react'

import { api } from '../../__data__/api/api'
import { ArrowUpIcon, LinkIcon } from '@chakra-ui/icons'
import { Course } from '../../__data__/model'
import { CourseDetails } from './course-details'

export const CourseCard = ({ course }: { course: Course }) => {
  const [getLessonList, populatedCourse] = api.useLazyGetCourseByIdQuery()
  const [isOpened, setIsOpened] = useState(false)
  useEffect(() => {
    if (isOpened) {
      getLessonList(course.id, true)
    }
  }, [isOpened])

  const handleToggleOpene = useCallback(() => {
    setIsOpened((opened) => !opened)
  }, [setIsOpened])

  return (
    <Card key={course._id} align="left">
      <CardHeader>
        <Heading as="h2" mt="0">
          {course.name}
        </Heading>
      </CardHeader>
      {isOpened && (
        <CardBody mt="16px">
          <Stack divider={<StackDivider />} spacing="8px">
            <Box as="span" textAlign="left">
              {`Дата начала курса - ${dayjs(course.startDt).format('DD MMMM YYYYг.')}`}
            </Box>
            <Box as="span" textAlign="left">
              Количество занятий - {course.lessons.length}
            </Box>

            {populatedCourse.isFetching && <Spinner />}
            {!populatedCourse.isFetching && populatedCourse.isSuccess && (
              <CourseDetails populatedCourse={populatedCourse.data} />
            )}

            {getNavigationsValue('link.journal.attendance') && (
              <Tooltip
                label="На страницу с лекциями"
                fontSize="12px"
                top="16px"
              >
                <Button
                  leftIcon={<LinkIcon />}
                  as={ConnectedLink}
                  variant="outline"
                  colorScheme="blue"
                  to={generatePath(
                    `${getNavigationsValue('journal.main')}${getNavigationsValue('link.journal.attendance')}`,
                    { courseId: course.id },
                  )}
                >
                  <Box mt={3}></Box>
                  Посещаемость
                </Button>
              </Tooltip>
            )}
          </Stack>
        </CardBody>
      )}
      <CardFooter>
        <ButtonGroup
          spacing={[0, 4]}
          mt="16px"
          flexDirection={['column', 'row']}
        >
          <Tooltip label="На страницу с лекциями" fontSize="12px" top="16px">
            <Button
              leftIcon={<LinkIcon />}
              as={ConnectedLink}
              colorScheme="blue"
              to={`${getNavigationsValue('journal.main')}/lessons-list/${course._id}`}
            >
              Открыть
            </Button>
          </Tooltip>
          <Tooltip label="Детали" fontSize="12px" top="16px">
            <Button
              colorScheme="blue"
              mt={['16px', 0]}
              variant="outline"
              leftIcon={
                <ArrowUpIcon
                  transform={isOpened ? 'rotate(0)' : 'rotate(180deg)'}
                />
              }
              loadingText="Загрузка"
              isLoading={populatedCourse.isFetching}
              onClick={handleToggleOpene}
            >
              {isOpened ? 'Закрыть' : 'Просмотреть детали'}
            </Button>
          </Tooltip>
        </ButtonGroup>
      </CardFooter>
    </Card>
  )
}
