import React, { useCallback, useEffect, useRef, useState } from 'react'
import dayjs from 'dayjs'
import { Link } from 'react-router-dom'
import { getConfigValue, getNavigationsValue } from '@ijl/cli'

import {
  Box,
  CardHeader,
  CardBody,
  CardFooter,
  ButtonGroup,
  Stack,
  StackDivider,
  Button,
  UnorderedList,
  Heading,
  Tooltip,
} from '@chakra-ui/react'

import {
  ArrowImg,
  IconButton,
  InputElement,
  InputLabel,
  InputWrapper,
  StartWrapper,
  Papper,
  ErrorSpan,
  Cross,
  AddButton,
  MainWrapper,
  StyledCard,
} from './style'

import { linkOpen, moreDetails } from '../assets'

import arrow from '../assets/36-arrow-right.svg'
import { keycloak } from '../__data__/kc'
import { useAppSelector } from '../__data__/store'
import { api } from '../__data__/api/api'
import { isTeacher } from '../utils/user'

const CoursesList = () => {
  const user = useAppSelector((s) => s.user)
  const { data, isLoading, error } = api.useCoursesListQuery()
  const [createCourse, crcQuery] = api.useCreateUpdateCourseMutation()
  const [value, setValue] = useState('')
  const [showForm, setShowForm] = useState(false)
  const [showDetails, setShowDetails] = useState(false)

  const handleChange = useCallback(
    (event) => {
      setValue(event.target.value.toUpperCase())
    },
    [setValue],
  )
  const handleSubmit = useCallback(
    (event) => {
      event.preventDefault()
      createCourse({ name: value })
    },
    [value],
  )

  useEffect(() => {
    if (crcQuery.isSuccess) {
      setValue('')
    }
  }, [crcQuery.isSuccess])

  return (
    <MainWrapper>
      <StartWrapper>
        {isTeacher(user) && (
          <>
            {showForm ? (
              <Papper>
                <Cross role="button" onClick={() => setShowForm(false)}>
                  X
                </Cross>
                <form onSubmit={handleSubmit}>
                  <InputWrapper>
                    <InputLabel htmlFor="input">
                      Название новой лекции:
                    </InputLabel>
                    <InputElement
                      value={value}
                      onChange={handleChange}
                      id="input"
                      type="text"
                      autoComplete="off"
                    />
                    <IconButton type="submit">
                      <ArrowImg src={arrow} />
                    </IconButton>
                  </InputWrapper>
                  {crcQuery?.error && (
                    <ErrorSpan>{(crcQuery?.error as any).error}</ErrorSpan>
                  )}
                </form>
              </Papper>
            ) : (
              <AddButton onClick={() => setShowForm(true)}>Добавить</AddButton>
            )}
          </>
        )}
        <UnorderedList spacing={3}>
          {data?.body?.map((course) => (
            <StyledCard key={course._id} align="left">
              <CardHeader>
                <Heading as="h2" mt="0">
                  {course.name}
                </Heading>
              </CardHeader>
              {showDetails && (
                <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>
                  </Stack>
                </CardBody>
              )}
              <CardFooter>
                <ButtonGroup spacing="12" mt="16px">
                  <Tooltip
                    label="На страницу с лекциями"
                    fontSize="12px"
                    top="16px"
                  >
                    <Button variant="ghost" border="none" bg="#ffffff">
                      <Link
                        to={`${getNavigationsValue('journal.main')}/lessons-list/${course._id}`}
                      >
                        <img src={linkOpen} alt="Перейти к лекциям" />
                      </Link>
                    </Button>
                  </Tooltip>
                  <Tooltip label="Детали" fontSize="12px" top="16px">
                    <Button
                      variant="ghost"
                      border="none"
                      bg="#ffffff"
                      onClick={() => {
                        showDetails
                          ? setShowDetails(null)
                          : setShowDetails(true)
                      }}
                      cursor="pointer"
                    >
                      <img src={moreDetails} alt="Просмотреть детали" />
                    </Button>
                  </Tooltip>
                </ButtonGroup>
              </CardFooter>
            </StyledCard>
          ))}
        </UnorderedList>
      </StartWrapper>
    </MainWrapper>
  )
}

export default CoursesList
