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,
} 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 [lessons, setLessons] = useState(null);
  const user = useAppSelector((s) => s.user);
  const { data, isLoading, error } = api.useLessonListQuery();

  useEffect(() => {
    const check = async () => {
      if (keycloak.authenticated) {
        keycloak;
        const rq = await fetch(`${getConfigValue("journal.back.url")}/check`, {
          headers: {
            accept: "application/json",
            authorization: `Bearer ${keycloak.token}`,
          },
        });
        const data = await rq.json();

        console.log("check", data);
      } else {
        keycloak.onAuthSuccess = check;
      }
    };

    check();
  }, []);

  const [answer, setAnswer] = useState(null);

  const send = async () => {
    if (keycloak.authenticated) {
      keycloak;
      const rq = await fetch(`${getConfigValue("journal.back.url")}/test`, {
        headers: {
          accept: "application/json",
          authorization: `Bearer ${keycloak.token}`,
        },
      });
      const data = await rq.json();
      setAnswer(data);
    } else {
      setAnswer({ message: "Пользователь не авторизован" });
    }
  };

  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>
      {isTeacher(user) && (
        <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 }}>
        {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>
  );
};
