import { intervalToDuration } from "date-fns";
import FlashIcon from "../icons/FlashIcon";
import Button from "../Button";
import useModalStore from "../../stores/useModalStore";
import { Session } from "../../types/Session";
import { useEffect, useState } from "react";
import EndSessionModal from "./EndSessionModal";
import ClientCard from "../ClientCard";
import { useQuery } from "@tanstack/react-query";
import api from "../../utils/api";
import { Client } from "../../types/Client";

function CurrentSessionModal({ session }: { session: Session }) {
  const { setModal } = useModalStore();

  const [now, setNow] = useState(Date.now());

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

  const { data: client } = useQuery({
    queryKey: ["client", session.clientId],
    queryFn: () => api.get(`clients/${session.clientId}`).json<Client>(),
  });

  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>
          {client && <ClientCard client={client} />}
        </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.manager.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;
