import React, { useEffect, useRef, useState } from 'react'
import dayjs from 'dayjs'
import { Link } from 'react-router-dom'
import { getNavigationsValue, getFeatures } from '@brojs/cli'
import {
  Button,
  Tr,
  Td,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  useToast,
} from '@chakra-ui/react'
import { EditIcon } from '@chakra-ui/icons'

import { qrCode } from '../../../assets'

import { LessonForm } from './lessons-form'
import { api } from '../../../__data__/api/api'

const features = getFeatures('journal')
const groupByDate = features?.['group.by.date']

type ItemProps = {
  id: string
  date: string
  name: string
  isTeacher: boolean
  courseId: string
  setlessonToDelete(): void
  students: unknown[]
}

export const Item: React.FC<ItemProps> = ({
  id,
  date,
  name,
  isTeacher,
  courseId,
  setlessonToDelete,
  students,
}) => {
  const [edit, setEdit] = useState(false)
  const toastRef = useRef(null)
  const toast = useToast()
  const [updateLesson, updateLessonRqst] = api.useUpdateLessonMutation()
  const createdLessonRef = useRef(null)

  const onSubmit = (lessonData) => {
    toastRef.current = toast({
      title: 'Отправляем',
      status: 'loading',
      duration: 9000,
    })
    createdLessonRef.current = lessonData
    if (navigator.onLine) {
      updateLesson(lessonData)
    } else {
      toast.update(toastRef.current, {
        title: 'Отсутствует интернет',
        status: 'error',
        duration: 3000
      })
    }
  }

  useEffect(() => {
    if (updateLessonRqst.isSuccess) {
      const toastProps = {
        title: 'Лекция Обновлена',
        description: `Лекция ${createdLessonRef.current?.name} успешно обновлена`,
        status: 'success' as const,
        duration: 9000,
        isClosable: true,
      }
      if (toastRef.current) toast.update(toastRef.current, toastProps)
      else toast(toastProps)
      setEdit(false)
    }
  }, [updateLessonRqst.isSuccess])

  if (edit && isTeacher) {
    return (
      <Tr>
        <Td colSpan={5}>
          <LessonForm
            isLoading={updateLessonRqst.isLoading}
            error={(updateLessonRqst.error as any)?.error}
            onSubmit={onSubmit}
            onCancel={() => {
              setEdit(false)
            }}
            lesson={{ _id: id, id, name, date }}
            title={'Редактирование лекции'}
            nameButton={'Сохранить'}
          />
        </Td>
      </Tr>
    )
  }

  return (
    <Tr>
      {isTeacher && (
        <Td>
          <Link
            to={`${getNavigationsValue('journal.main')}/lesson/${courseId}/${id}`}
            style={{ display: 'flex' }}
          >
            <img width={24} src={qrCode} style={{ margin: '0 auto' }} />
          </Link>
        </Td>
      )}
      <Td textAlign="center">
        {dayjs(date).format(groupByDate ? 'HH:mm' : 'HH:mm DD.MM.YY')}
      </Td>
      <Td>{name}</Td>
      {isTeacher && (
        <Td>
          {!edit && (
            <Menu>
              <MenuButton as={Button}>
                <EditIcon />
              </MenuButton>
              <MenuList>
                <MenuItem
                  onClick={() => {
                    setEdit(true)
                  }}
                >
                  Edit
                </MenuItem>
                <MenuItem onClick={setlessonToDelete}>Delete</MenuItem>
              </MenuList>
            </Menu>
          )}
          {edit && <Button onClick={setlessonToDelete}>Сохранить</Button>}
        </Td>
      )}
      <Td isNumeric>{students.length}</Td>
    </Tr>
  )
}
