import React, { useCallback, useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';
import { Link } from 'react-router-dom'

import {
  ArrowImg,
  IconButton,
  InputElement,
  InputLabel,
  InputWrapper,
  StartWrapper,
  LessonItem,
  Lessonname,
} from './style';

import arrow from '../assets/36-arrow-right.svg';
import { connect, getSocket } from "../socket";

export const Journal = () => {
  const [lessons, setLessons] = useState(null);

  useEffect(() => {
    connect();
    const socket = getSocket();
    socket.on('lessons', data => {
      setLessons(data)
    })
  }, []);

  const [value, setValue] = useState('');
  const handleChange = useCallback(event => {
    setValue(event.target.value.toUpperCase())
  }, [setValue]);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleSubmit = useCallback((event) => {
    event.preventDefault();

    const socket = getSocket();
    socket.emit('create-lesson', { lessonName: value });
    setValue('')
  }, [value])

  return (
    <StartWrapper>
      <form onSubmit={handleSubmit}>
        <InputWrapper>
          <InputLabel
            htmlFor='input'
          >
            Название новой лекции:
          </InputLabel>
          <InputElement
            value={value}
            onChange={handleChange}
            ref={inputRef}
            id="input"
            type="text"
            autoComplete="off"
          />
          <IconButton type="submit">
            <ArrowImg src={arrow} />
          </IconButton>
        </InputWrapper>
      </form>
      <ul style={{ paddingLeft: 0 }}>
        {lessons?.map((lesson) => (
          <LessonItem key={lesson.id}>
            <Link to={`/journal/l/${lesson.id}`}>
              <Lessonname>{lesson.name}</Lessonname>
              <span>{dayjs(lesson.ts).format('DD MMMM YYYYг.')}</span>
            </Link>
          </LessonItem>
        ))}
      </ul>
    </StartWrapper>
  )
};
