import { intervalToDuration } from "date-fns";
import FlashIcon from "../icons/FlashIcon";
import Button from "../Button";
import ChevronRightIcon from "../icons/ChevronRightIcon";
import useModalStore from "../../stores/useModalStore";
import { Session } from "../../types/Session";
import { useEffect, useState } from "react";
import EndSessionModal from "./EndSessionModal";

function CurrentSessionModal({ session }: { session: Session }) {
  // const queryClient = useQueryClient();

  const { setModal } = useModalStore();

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

  useEffect(() => {
    const interval = setInterval(() => {
      setNow(Date.now());
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  if (!session) return null;

  return (
    <div className="w-[25vw] bg-[#FFFFFF] rounded-[2.222vw] px-[1.389vw] pb-[1.389vw]">
      <h2 className="title-s font-medium text-center py-[1.806vw]">
        Текущий сеанс
      </h2>
      <div className="flex flex-col gap-[1.667vw]">
        <div className="py-[1.389vw] flex gap-[0.833vw] border border-b-[#F6F6F6] border-t-0 border-r-0 border-l-0">
          <div className='size-[4.444vw] bg-[#F6F6F6] rounded-[0.833vw] bg-[url("/images/super-table.png")] bg-no-repeat bg-[length:2.222vw] bg-center'></div>
          <div className="flex flex-col gap-[0.278vw] self-center ">
            <div className="flex gap-[0.278vw]">
              <p className="title-s font-medium">{session.server.name}</p>
              <p className="flex justify-center items-center gap-[0.139vw] caption-s font-medium text-[#7B60F3]">
                <span className="size-[0.833vw] text-[#7B60F3]">
                  <FlashIcon />
                </span>
                Сеанс идёт{" "}
                {(() => {
                  const duration = intervalToDuration({
                    start: session.createdAt,
                    end: now,
                  });
                  const hours = (duration.hours || 0)
                    .toString()
                    .padStart(2, "0");
                  const minutes = (duration.minutes || 0)
                    .toString()
                    .padStart(2, "0");
                  const seconds = (duration.seconds || 0)
                    .toString()
                    .padStart(2, "0");
                  return `${hours}:${minutes}:${seconds}`;
                })()}
              </p>
            </div>
            <div>
              <p className="caption-s font-medium text-[#BDBDBD]">
                {session.server.description}
              </p>
            </div>
          </div>
        </div>
        <div className="flex flex-col gap-[0.833vw]">
          <h2 className="title-s font-medium">Параметры сеанса</h2>
          <div>
            <Button variant="secondary" className="w-full">
              <div className="flex flex-col gap-[0.278vw] w-full text-left h-[2.222vw]">
                <p className="caption-s font-medium text-[#BDBDBD]">Клиент</p>
                <p className="text-s font-medium">{session.client.name}</p>
              </div>
              <div className="flex gap-[0.556vw] items-center">
                {!session.client.email && (
                  <p className="caption-s font-medium text-[#7B60F3] whitespace-nowrap">
                    Добавьте email
                  </p>
                )}
                <span className="w-[1.389vw] h-[1.389vw] flex items-center justify-center text-[#7B60F3]">
                  <ChevronRightIcon />
                </span>
              </div>
            </Button>
          </div>
        </div>
        <div className="flex flex-col gap-[0.833vw]">
          <h2 className="title-s font-medium">Детали</h2>
          <div className="flex flex-col gap-[0.556vw]">
            <div className="flex gap-[0.556vw]">
              <p className="caption-s font-medium text-[#BDBDBD]">Менеджер:</p>
              <p className="caption-s font-medium">{session.owner.fullname}</p>
            </div>
            <div className="flex gap-[0.556vw]">
              <p className="caption-s font-medium text-[#BDBDBD]">
                Сценарии проживания:
              </p>
              <p className="caption-s font-medium">Добавить в бэкенд</p>
            </div>
          </div>
        </div>
        <div className="flex flex-col gap-[0.556vw]">
          <Button
            size="large"
            variant="critical"
            className="w-full"
            onClick={() => {
              setModal(<EndSessionModal session={session} />);
            }}
          >
            Завершить сеанс
          </Button>
          <Button
            size="large"
            variant="primary"
            className="w-full"
            onClick={() => setModal(null)}
          >
            Закрыть
          </Button>
        </div>
      </div>
    </div>
  );
}

export default CurrentSessionModal;
