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

import {
  ArrowImg,
  IconButton,
  InputElement,
  InputLabel,
  InputWrapper,
  StartWrapper,
  LessonItem,
  Lessonname,
  Papper,
  ErrorSpan,
  Cross,
  AddButton,
} 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'

export const Journal = () => {
  const user = useAppSelector((s) => s.user)
  const { data, isLoading, error } = api.useLessonListQuery()
  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 })
    },
    [value],
  )

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

  return (
    <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>
                {crLQuery.error && (
                  <ErrorSpan>{crLQuery.error.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) ? `/journal/l/${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>
  )
}
