import { Button, Flex } from "antd";
import { CheckOutlined } from "@ant-design/icons";
import HeaderBar from "core/components/Header";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { Constants } from "core/utils/utils";
import React, { useEffect } from "react";
import MyErrorResult from "shared/components/MyResult";
import MyEmpty from "shared/components/MyEmpty";
import { useGetLessonContentsQuery } from "core/services/lessons";
import MyMiddleCard from "shared/components/MyMiddleCard";
import { Converter } from "../converter";
import Questions from "../Questions";
import {
  addWebSocketReconnectListener,
  removeWebSocketReconnectListener,
} from "core/services/websocketService";
import { useDispatch, useSelector } from "react-redux";
import {
  lessonPageContents,
  setLessonPageContents,
  setLessonPageCurrentLessonId,
} from "./lessonPageSlice";
import MyCenteredSpin from "shared/components/MyCenteredSpin";

const LessonContents: React.FC = () => {
  const dispatch = useDispatch();
  const { lessonId } = useParams();

  const lessonContents = useSelector(lessonPageContents);

  const { data, error, isLoading, refetch } = useGetLessonContentsQuery(
    lessonId as string,
    {
      refetchOnMountOrArgChange: true,
    }
  );

  useEffect(() => {
    dispatch(setLessonPageCurrentLessonId(lessonId as string));
    addWebSocketReconnectListener(refetch);

    return () => removeWebSocketReconnectListener(refetch);
  }, []);

  useEffect(() => {
    if (!data) return;

    dispatch(setLessonPageContents(data));
  }, [data]);

  if (isLoading) return <MyCenteredSpin height="140px" />;
  if (error) return <MyErrorResult />;

  if (!lessonContents || lessonContents.length === 0) return <MyEmpty />;

  return (
    <>
      {lessonContents.map((lessonContent) => (
        <div key={lessonContent.Id} style={{ paddingBottom: 6 }}>
          <Converter mode="view" lessonContent={lessonContent} />
        </div>
      ))}
    </>
  );
};

export default function LessonPage() {
  const location = useLocation();
  const navigate = useNavigate();

  return (
    <>
      <HeaderBar
        theme="light"
        backTo={Constants.ROUTE_PATHS.LESSIONS.ROOT}
        onEdit={() => navigate(`${location.pathname}/editor`)}
      />

      <MyMiddleCard
        outOfCardChildren={
          <div style={{ marginTop: 24 }}>
            <Questions lessionID={"lessionID"} />
          </div>
        }
      >
        <LessonContents />

        <Flex justify="right">
          <Button type="primary" icon={<CheckOutlined />}>
            Finish lesson
          </Button>
        </Flex>
      </MyMiddleCard>
    </>
  );
}
