import React, { useCallback, useEffect, useRef, useState } from 'react'
import dayjs from 'dayjs'
import { Link, useParams } from 'react-router-dom'
import { getNavigationsValue } from '@ijl/cli'
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
} from '@chakra-ui/react'

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

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 LessonList = () => {
  const { courseId } = useParams()
  const user = useAppSelector((s) => s.user)
  const { data, isLoading, error } = api.useLessonListQuery(courseId)
  const [createLesson, crLQuery] = api.useCreateLessonMutation()
  const [value, setValue] = useState('')
  const [showForm, setShowForm] = useState(false)

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

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

  return (
    <MainWrapper>
      <StartWrapper>
        <Breadcrumb>
          <BreadcrumbItem>
            <Link as={BreadcrumbLink} to={getNavigationsValue('journal.main')}>Журнал</Link>
          </BreadcrumbItem>

          <BreadcrumbItem isCurrentPage>
            <BreadcrumbLink href="#">Курс</BreadcrumbLink>
          </BreadcrumbItem>
        </Breadcrumb>

        {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>
                  {crLQuery.error && (
                    <ErrorSpan>{(crLQuery.error as any).error}</ErrorSpan>
                  )}
                </form>
              </Papper>
            ) : (
              <AddButton onClick={() => setShowForm(true)}>Добавить</AddButton>
            )}
          </>
        )}
        <ul style={{ paddingLeft: 0 }}>
          {data?.body?.map((lesson) => (
            <LessonItem key={lesson._id}>
              <Link
                to={
                  isTeacher(user)
                    ? `${getNavigationsValue('journal.main')}/lesson/${courseId}/${lesson._id}`
                    : ''
                }
                style={{ display: 'flex' }}
              >
                <Lessonname>{lesson.name}</Lessonname>
                <span>{dayjs(lesson.date).format('DD MMMM YYYYг.')}</span>
                <span style={{ marginLeft: 'auto' }}>
                  Участников - {lesson.students.length}
                </span>
              </Link>
            </LessonItem>
          ))}
        </ul>
      </StartWrapper>
    </MainWrapper>
  )
}

export default LessonList
