/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-irregular-whitespace */
import { format, parse } from "date-fns";
import useSidebarTabStore from "../stores/useSidebarStore";
import ArrowRightIcon from "./icons/ArrowRightIcon";
import CloseIcon from "./icons/CloseIcon";
import { enUS, ru } from "date-fns/locale";
import ky from "ky";
import { Trans } from "react-i18next";
import i18n from "../i18n";
import { useState } from "react";
import LoaderIcon from "./icons/LoaderIcon";
import api from "../utils/api";

function SidebarTab4() {
  const {
    currentTab,
    setCurrentTab,
    setIsOpen,
    selectedDay,
    selectedTime,
    name,
    phone,
    email,
    buildId,
    setUrl,
  } = useSidebarTabStore();

  const [isLoading, setIsLoading] = useState<boolean>(false);

  async function sendInvite(email: string, link: string) {
    try {
      const reuslt: any = await api
        .post("sendInvite", { json: { email, link } })
        .json();
      console.log("reuslt", reuslt);
    } catch (error) {
      console.log({ error: (error as Error).message });
    }
  }

  async function handleClickSignUp() {
    if (!selectedTime || !selectedDay) {
      return;
    }

    setIsLoading(true);

    const startAt = parse(selectedTime, "HH:mm", selectedDay);

    try {
      const result: any = await ky
        .post(`${import.meta.env.VITE_CRM_API_URL}/scheduled_sessions`, {
          json: {
            buildId,
            startAt,
            client: {
              name,
              phone,
              email,
            },
          },
        })
        .json();

      sendInvite(email, result.url);
      setUrl(result.url);
      setCurrentTab(currentTab + 1);
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      if (error instanceof Error) {
        alert(error.message);
      }
    }
  }

  return (
    <div className="sm:p-8 p-6 flex flex-col justify-between sm:gap-8 gap-6 min-h-full">
      <div>
        <div className="flex items-start justify-between">
          <p className="text-2xl text-gradient font-semibold font-gilroy w-fit leading-snug">
            <Trans i18nKey={"sidebar.title3"}>Проверка заявки</Trans>
          </p>
          <button
            onClick={() => setIsOpen(false)}
            className="transition-opacity hover:opacity-50"
          >
            <CloseIcon />
          </button>
        </div>

        <div className="sm:mt-6 mt-4">
          <div className="sm:mt-6 mt-4 sm:p-6 p-4 flex flex-col gap-6 font-semibold font-gilroy border border-[#3D425C] ">
            <p className="leading-tight">
              <Trans i18nKey={"sidebar.sessionDetails"}>Детали сеанса</Trans>
            </p>
            <div className="flex flex-col gap-2">
              <div className="flex justify-between sm:text-base text-sm">
                <p className="opacity-50">
                  <Trans i18nKey={"sidebar.date"}>Дата</Trans>
                </p>
                <p>
                  {selectedDay &&
                    format(
                      selectedDay,
                      "dd MMMM",
                      i18n.language === "ru" ? { locale: ru } : { locale: enUS }
                    )}
                </p>
              </div>
              <div className="flex justify-between sm:text-base text-sm">
                <p className="opacity-50">
                  <Trans i18nKey={"sidebar.time"}>Время</Trans>
                </p>
                <p>{selectedTime}</p>
              </div>
            </div>
          </div>

          <div className="sm:p-6 p-4 flex flex-col gap-6 font-semibold font-gilroy border border-[#3D425C] border-t-0">
            <p className="leading-tight">
              <Trans i18nKey={"sidebar.contactDetails"}>
                Контактные данные
              </Trans>
            </p>
            <div className="flex flex-col gap-2">
              <div className="flex justify-between sm:text-base text-sm">
                <p className="opacity-50">
                  <Trans i18nKey={"sidebar.name"}>Имя</Trans>
                </p>
                <p>{name}</p>
              </div>
              <div className="flex justify-between sm:text-base text-sm">
                <p className="opacity-50">
                  <Trans i18nKey={"sidebar.phone"}>Телефон</Trans>
                </p>
                <p>{phone}</p>
              </div>
              <div className="flex justify-between sm:text-base text-sm">
                <p className="opacity-50">Email</p>
                <p>{email}</p>
              </div>
            </div>
          </div>

          <div className="sm:p-6 p-4 border border-t-0 border-[#3D425C]">
            <p className="text-xs">
              <Trans i18nKey={"sidebar.submitNotice1"}>
                Нажимая кнопку записаться, вы принимаете
              </Trans>{" "}
              <a href="#" className="text-[#798FFF]">
                <Trans i18nKey={"sidebar.submitNotice2"}>
                  условия использования
                </Trans>
              </a>{" "}
              <Trans i18nKey={"sidebar.submitNotice3"}>и</Trans>{" "}
              <a href="#" className="text-[#798FFF]">
                <Trans i18nKey={"sidebar.submitNotice4"}>
                  политику конфиденциальности
                </Trans>
              </a>
            </p>
          </div>
        </div>
      </div>

      <div className="flex flex-col sm:gap-6 gap-4">
        <p className="text-center text-xs opacity-50 leading-tight">
          <Trans i18nKey={"sidebar.notice"}>
            Запись на демонстрацию работает в ознакомительном режиме и не
            сохраняет введенные данные
          </Trans>
        </p>

        <div className="flex sm:gap-4 gap-2">
          <button
            onClick={() => setCurrentTab(currentTab - 1)}
            className="px-6 py-4 border border-[#3D425C] rounded-full sm:text-base text-sm font-medium group w-fit"
          >
            <span className="opacity-80 transition-opacity group-hover:opacity-100">
              <Trans i18nKey={"sidebar.buttonBack"}>Назад</Trans>
            </span>
          </button>

          <button
            disabled={isLoading}
            onClick={() => void handleClickSignUp()}
            className="px-6 py-3 bg-gradient rounded-full sm:text-base text-sm font-medium flex items-center justify-between w-full disabled:opacity-75"
          >
            <span>
              <Trans i18nKey={"sidebar.buttonSignUp"}>Записаться</Trans>
            </span>
            {!isLoading ? (
              <ArrowRightIcon className="sm:w-8 sm:h-8 w-6 h-6" />
            ) : (
              <LoaderIcon className="sm:w-8 sm:h-8 w-6 h-6 animate-spin" />
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

export default SidebarTab4;
