import { useMutation } from "@tanstack/react-query";
import { useQueryClient } from "@tanstack/react-query";
import useModalStore from "../../stores/useModalStore";
import { Session } from "../../types/Session";
import Button from "../Button";
import CurrentSessionModal from "./CurrentSessionModal";
import api from "../../utils/api";
import SpinIcon from "../icons/SpinIcon";

function EndSessionModal({ session }: { session: Session }) {
  const queryClient = useQueryClient();
  const { setModal } = useModalStore();

  const { mutate: endSession, isPending } = useMutation({
    mutationKey: ["sessions", session.id],
    mutationFn: () =>
      api.put(`sessions/${session.id}`, { json: { status: "ending" } }),
    onMutate: () => {
      queryClient.invalidateQueries({ queryKey: ["sessions"] });
      queryClient.invalidateQueries({ queryKey: ["last-started"] });
      queryClient.invalidateQueries({ queryKey: ["servers"] });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["last-sessions"] });
      setModal(null);
    },
  });

  return (
    <div className="w-[25vw] bg-white rounded-[2.222vw]">
      {isPending ? (
        <div className="flex flex-col gap-[1.667vw] w-[25vw] justify-center items-center py-[1.806vw]">
          <div className="flex flex-col gap-[0.556vw] w-full items-center">
            <h2 className="title-m font-medium">Завершаем сеанс</h2>
            <p className="caption-m font-medium text-[#BDBDBD]">
              Сохраняем данные, чтобы ничего не потерять
            </p>
          </div>
          <span className="size-[4.444vw] animate-spin text-[#7B60F3] flex items-center justify-center">
            <SpinIcon />
          </span>
        </div>
      ) : (
        <>
          <h2 className="title-s font-medium text-center py-[1.806vw]">
            Текущий сеанс
          </h2>
          <div className="p-[1.389vw] flex flex-col gap-[1.667vw]">
            <div className="flex flex-col gap-[0.556vw]">
              <p className="title-m font-medium">
                Точно хотите завершить сеанс?
              </p>
              <p className="caption-m font-medium text-[#BDBDBD]">
                Текущий сеанс будет завершен немедленно
              </p>
            </div>
            <div className="flex flex-col gap-[0.556vw]">
              <Button
                size="large"
                variant="critical"
                className="w-full"
                onClick={() => endSession()}
                disabled={isPending}
              >
                Завершить сеанс
              </Button>
              <Button
                size="large"
                variant="primary"
                className="w-full"
                onClick={() =>
                  setModal(<CurrentSessionModal session={session} />)
                }
              >
                Отменить
              </Button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

export default EndSessionModal;
