/* 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";

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

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

  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}/scheduledSessions`, {
          json: {
            buildId,
            startAt,
            client: {
              name,
              phone,
              email,
            },
          },
        })
        .json();

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

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

        <div className="mt-4 sm:mt-6">
          <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 text-sm sm:text-base">
                <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 text-sm sm:text-base">
                <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 text-sm sm:text-base">
                <p className="opacity-50">
                  <Trans i18nKey={"sidebar.name"}>Имя</Trans>
                </p>
                <p>{name}</p>
              </div>
              <div className="flex justify-between text-sm sm:text-base">
                <p className="opacity-50">
                  <Trans i18nKey={"sidebar.phone"}>Телефон</Trans>
                </p>
                <p>{phone}</p>
              </div>
              <div className="flex justify-between text-sm sm:text-base">
                <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 gap-4 sm:gap-6">
        <p className="text-xs leading-tight text-center opacity-50">
          <Trans i18nKey={"sidebar.notice"}>
            Запись на демонстрацию работает в ознакомительном режиме и не
            сохраняет введенные данные
          </Trans>
        </p>

        <div className="flex gap-2 sm:gap-4">
          <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="transition-opacity opacity-80 group-hover:opacity-100">
              <Trans i18nKey={"sidebar.buttonBack"}>Назад</Trans>
            </span>
          </button>

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

export default SidebarTab4;
