/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable no-irregular-whitespace */
import "./App.css";
import { Trans, useTranslation } from "react-i18next";
import FeedbackForm from "./components/FeedbackForm";
import ArrowRightIcon from "./components/icons/ArrowRightIcon";
import LogoIcon from "./components/icons/LogoIcon";
import MailIcon from "./components/icons/MailIcon";
import PhoneIcon from "./components/icons/PhoneIcon";
import TelegramIcon from "./components/icons/TelegramIcon";
import VKIcon from "./components/icons/VKIcon";
import YouTubeIcon from "./components/icons/YouTubeIcon";
import Sidebar from "./components/Sidebar";
import Header from "./components/Header";
import { Transition } from "react-transition-group";
import useSidebarStore from "./stores/useSidebarStore";
import { useEffect, useState } from "react";
import ky from "ky";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Bounce, ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import api from "./utils/api";
import InfoIcon from "./components/icons/InfoIcon";

function App() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [isOpen, setIsOpen] = useSidebarStore((state) => [
    state.isOpen,
    state.setIsOpen,
  ]);
  const [loading, setLoading] = useState<boolean>(false);
  const [countdownTimer, setCountdownTimer] = useState(15);
  const { t, i18n } = useTranslation();
  const build = searchParams.get("build") || null;
  const type = searchParams.get("type") || "demo";

  function toastError(text: string) {
    toast.error(text, {
      icon: <InfoIcon className="text-red-500" />,
      position: "top-center",
      autoClose: 5000,
      hideProgressBar: false,
      closeOnClick: true,
      pauseOnHover: true,
      draggable: true,
      progress: undefined,
      theme: "light",
      transition: Bounce,
    });
  }

  async function getLang() {
    const { countryCode, error }: { countryCode: string; error: string } =
      await api.get("getCountryCode").json();

    if (!error && countryCode !== "RU") {
      i18n.changeLanguage("en");
    }
  }

  async function startStream(build: string) {
    const { countryCode, error }: { countryCode: string; error: string } =
      await api.get("getCountryCode").json();

    if (!countryCode) {
      toastError("Неизвестная ошибка при получении кода страны");
      return;
    }

    if (error) {
      toastError(error);
      return;
    }

    let location = "a1";

    if (searchParams.has("location")) {
      location = searchParams.get("location") as string;
    } else if (countryCode !== "RU") {
      location = "a2";
    }

    setLoading(true);

    try {
      const response: any = await ky
        .get(
          `${
            import.meta.env.VITE_COORD_URL
          }/start?location=${location}&build=${build}&type=${type}`
        )
        .json();

      if (response.stream) {
        setInterval(() => {
          setCountdownTimer((prev) => prev - 1);
        }, 1000);

        setTimeout(() => {
          navigate(`/stream/${response.stream}`);
        }, 15000);
      } else if (response.error) {
        toastError(response.error);
        setLoading(false);
      } else {
        toastError("Неизвестная ошибка");
        setLoading(false);
      }
    } catch (error) {
      if (error instanceof Error) {
        toastError(`Неизвестная ошибка 2: ${error.message}`);
      }
      setLoading(false);
    }
  }

  useEffect(() => {
    getLang();

    if (build) {
      void startStream(build);
    }
  }, []);

  useEffect(() => {
    document.title = t("title");
  }, [i18n.language]);

  return (
    <>
      {!loading ? (
        <>
          <div className="min-h-screen bg-[#14161F] text-white overflow-hidden">
            <div className="container mx-auto 2xl:px-10 lg:px-8 sm:px-6 px-4 max-w-[1600px]">
              <Header
              // handleChangeLang={(lang) => void i18n.changeLanguage(lang)}
              />

              <div className="2xl:mt-[72px] lg:mt-16 sm:mt-[88px] mt-14 relative">
                <div className="absolute flex justify-center items-center w-full -top-8 blur-sm">
                  <img src="/images/shapes/shape-1.svg" alt="" className="" />
                </div>

                <div className="grid sm:grid-cols-2 lg:gap-4 sm:gap-3 gap-4">
                  <p className="2xl:text-[64px] xl:text-[52px] text-[40px] text-gradient w-fit font-gilroy leading-none font-medium">
                    <Trans i18nKey={"main.title"}>
                      Доступные
                      <br />
                      демонстрации
                    </Trans>
                  </p>
                  <p className="lg:w-[368px] lg:text-base text-sm">
                    <Trans i18nKey={"main.desc"}>
                      Клиент из любой точки мира может посмотреть жилой
                      комплекс, даже на нулевом этапе строительства. Он выберет
                      лучшую планировку и оценит вид из окон своей будущей
                      квартиры.
                    </Trans>
                  </p>
                </div>

                <div className="sm:mt-16 mt-8 grid sm:grid-cols-2 lg:gap-4 sm:gap-3 gap-2">
                  <div
                    className="group relative sm:h-full h-[264px] bg-gray-700 bg-no-repeat bg-center bg-cover"
                    style={{
                      backgroundImage: `url("/images/cards/upside.jpg")`,
                    }}
                  >
                    <div className="bg-gradient-card h-full transition-opacity group-hover:opacity-60 duration-300"></div>

                    <div className="p-6 absolute bottom-0 space-y-6">
                      <div>
                        <p className="xl:text-2xl text-xl font-gilroy font-semibold">
                          <Trans i18nKey={"main.cards.title4"}>
                            ЖК «Upside Towers»
                          </Trans>
                        </p>
                        <p className="lg:text-sm text-xs">
                          <Trans i18nKey={"main.cards.city3"}>
                            Россия, Москва
                          </Trans>
                        </p>
                      </div>

                      <button
                        onClick={() => void startStream("upsideTowersDev")}
                        className="flex bg-gradient rounded-full p-2 gap-0 group-hover:gap-1 group-hover:pr-4 group-hover:pl-6 transition-all duration-300"
                      >
                        <span className="font-medium w-0 opacity-0 group-hover:w-[82px] group-hover:opacity-100 overflow-hidden transition-all duration-300">
                          <Trans i18nKey={"main.cards.button"}>Запустить</Trans>
                        </span>
                        <ArrowRightIcon />
                      </button>
                    </div>
                  </div>

                  <div className="grid lg:grid-cols-2 lg:gap-4 sm:gap-3 gap-2">
                    {i18n.language === "ru" ? (
                      <>
                        <div
                          className="group relative lg:h-[508px] sm:h-[284px] h-[264px] col-span-1 bg-gray-700 bg-no-repeat bg-center bg-cover"
                          style={{
                            backgroundImage: `url("/images/cards/nks.jpg")`,
                          }}
                        >
                          <div className="bg-gradient-card h-full transition-opacity group-hover:opacity-50 duration-300"></div>

                          <div className="p-6 absolute bottom-0 space-y-6">
                            <div>
                              <p className="xl:text-2xl text-xl font-gilroy font-semibold">
                                <Trans i18nKey={"main.cards.title"}>
                                  МФК «Revolution towers»
                                </Trans>
                              </p>
                              <p className="lg:text-sm text-xs">
                                <Trans i18nKey={"main.cards.city1"}>
                                  Россия, Екатеринбург
                                </Trans>
                              </p>
                            </div>

                            <button
                              onClick={() => void startStream("nksJukovaDev")}
                              className="flex bg-gradient rounded-full p-2 gap-0 group-hover:gap-1 group-hover:pr-4 group-hover:pl-6 transition-all duration-300"
                            >
                              <span className="font-medium w-0 opacity-0 group-hover:w-[82px] group-hover:opacity-100 overflow-hidden transition-all duration-300">
                                <Trans i18nKey={"main.cards.button"}>
                                  Запустить
                                </Trans>
                              </span>
                              <ArrowRightIcon />
                            </button>
                          </div>
                        </div>

                        <div
                          className="group relative lg:h-[508px] sm:h-[284px] h-[264px] col-span-1 bg-gray-700 bg-no-repeat bg-center bg-cover"
                          style={{
                            backgroundImage: `url("/images/cards/liferes.jpg")`,
                          }}
                        >
                          <div className="bg-gradient-card h-full transition-opacity group-hover:opacity-50 duration-300"></div>

                          <div className="p-6 absolute bottom-0 space-y-6">
                            <div>
                              <p className="xl:text-2xl text-xl font-gilroy font-semibold">
                                <Trans i18nKey={"main.cards.title2"}>
                                  ЖК «Life Резиденция»
                                </Trans>
                              </p>
                              <p className="lg:text-sm text-xs">
                                <Trans i18nKey={"main.cards.city2"}>
                                  Россия, Тюмень
                                </Trans>
                              </p>
                            </div>

                            <button
                              onClick={() => void startStream("lifeResidence")}
                              className="flex bg-gradient rounded-full p-2 gap-0 group-hover:gap-1 group-hover:pr-4 group-hover:pl-6 transition-all duration-300"
                            >
                              <span className="font-medium w-0 opacity-0 group-hover:w-[82px] group-hover:opacity-100 overflow-hidden transition-all duration-300">
                                <Trans i18nKey={"main.cards.button"}>
                                  Запустить
                                </Trans>
                              </span>
                              <ArrowRightIcon />
                            </button>
                          </div>
                        </div>

                        {/* <div
                          className="group relative lg:h-[508px] sm:h-[284px] h-[264px] col-span-1 bg-gray-700 bg-no-repeat bg-center bg-cover"
                          style={{
                            backgroundImage: `url("/images/cards/aivaz.jpg")`,
                          }}
                        >
                          <div className="bg-gradient-card h-full transition-opacity group-hover:opacity-90 duration-300"></div>

                          <div className="p-6 absolute bottom-0 space-y-6">
                            <div>
                              <p className="xl:text-2xl text-xl font-gilroy font-semibold">
                                <Trans i18nKey={"main.cards.title3"}>
                                  ЖК «Айвазовский City»
                                </Trans>
                              </p>
                              <p className="lg:text-sm text-xs">
                                <Trans i18nKey={"main.cards.city2"}>
                                  Россия, Тюмень
                                </Trans>
                              </p>
                            </div>

                            <button
                              onClick={() => void startStream("IvazowskyDev")}
                              className="flex bg-gradient rounded-full p-2 gap-0 group-hover:gap-1 group-hover:pr-4 group-hover:pl-6 transition-all duration-300"
                            >
                              <span className="font-medium w-0 opacity-0 group-hover:w-[82px] group-hover:opacity-100 overflow-hidden transition-all duration-300">
                                <Trans i18nKey={"main.cards.button"}>
                                  Запустить
                                </Trans>
                              </span>
                              <ArrowRightIcon />
                            </button>
                          </div>
                        </div> */}
                      </>
                    ) : (
                      <div
                        className="group relative lg:h-[508px] sm:h-[284px] h-[264px] col-span-2 bg-gray-700 bg-no-repeat bg-center bg-cover"
                        style={{
                          backgroundImage: `url("/images/cards/shipyard.jpg")`,
                        }}
                      >
                        <div className="bg-gradient-card h-full transition-opacity group-hover:opacity-90 duration-300"></div>

                        <div className="p-6 absolute bottom-0 space-y-6">
                          <div>
                            <p className="xl:text-2xl text-xl font-gilroy font-semibold">
                              IMI Saudi Shipyard
                            </p>
                            <p className="lg:text-sm text-xs">Saudi Arabia</p>
                          </div>

                          <button
                            onClick={() => void startStream("ShipyardSaudiDev")}
                            className="flex bg-gradient rounded-full p-2 gap-0 group-hover:gap-1 group-hover:pr-4 group-hover:pl-6 transition-all duration-300"
                          >
                            <span className="font-medium w-0 opacity-0 group-hover:w-[82px] group-hover:opacity-100 overflow-hidden transition-all duration-300">
                              <Trans i18nKey={"main.cards.button"}>
                                Запустить
                              </Trans>
                            </span>
                            <ArrowRightIcon />
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              <div className="lg:mt-40 sm:mt-[120px] mt-[88px]">
                <div className=" grid xl:grid-cols-3 lg:grid-cols-2 lg:gap-4 gap-8">
                  <div className="flex flex-col justify-between gap-8 pb-4 border-b border-[#3D425C]">
                    <div className="flex flex-col xl:gap-8 gap-6">
                      <p className="2xl:text-[64px] xl:text-5xl text-[40px] text-gradient font-gilroy w-fit leading-none font-medium">
                        <Trans i18nKey={"signUp.title"}>
                          Запись на
                          <br />
                          удаленную
                          <br />
                          демонстрацию
                        </Trans>
                      </p>
                      <p className="2xl:text-base text-sm">
                        <Trans i18nKey={"signUp.desc"}>
                          Запись на демонстрацию может быть
                          <br />
                          оформлена в виде блока на сайте
                          <br />
                          застройщика или жилого комплекса.
                        </Trans>
                      </p>
                      <button
                        onClick={() => setIsOpen(true)}
                        className="group relative px-6 py-2 bg-gradient rounded-full lg:text-base text-sm font-medium leading-normal w-fit"
                      >
                        <div className="absolute top-0 left-0 w-full h-full rounded-full bg-black opacity-0 group-hover:opacity-10 transition-all"></div>
                        <span className="relative">
                          <Trans i18nKey={"signUp.button"}>Записаться</Trans>
                        </span>
                      </button>
                    </div>
                    <p className="2xl:text-sm text-xs text-[#52587A]">
                      <Trans i18nKey={"signUp.notice"}>
                        Запись доступна в демонстрационном режиме.
                        <br />
                        Указанные при записи данные не будут сохранены.
                      </Trans>
                    </p>
                  </div>

                  <div className="xl:col-span-2">
                    <video
                      src="/videos/video.mp4"
                      playsInline
                      autoPlay
                      muted
                      loop
                    ></video>
                  </div>
                </div>
              </div>

              <div className="lg:mt-40 sm:mt-[120px] mt-[88px]">
                <div className="grid lg:grid-cols-4 grid-cols-1 lg:gap-4 gap-6">
                  <div className="col-span-1">
                    <div className="grid lg:grid-cols-1 sm:grid-cols-2 lg:gap-6 gap-4">
                      <p className="2xl:text-[64px] xl:text-5xl text-[40px] font-gilroy text-gradient font-medium w-fit leading-none">
                        <Trans i18nKey={"feedback.title"}>
                          Свяжитесь
                          <br />с нами
                        </Trans>
                      </p>
                      <p className="2xl:text-xl lg:text-lg font-gilroy font-semibold leading-tight">
                        <Trans i18nKey={"feedback.desc"}>
                          Хотите увеличить конверсию?
                          <br />
                          Давайте обсудим детали!
                        </Trans>
                      </p>
                    </div>
                  </div>

                  <div className="lg:col-span-3">
                    <FeedbackForm />
                  </div>
                </div>
              </div>

              <div className="mt-[104px] relative">
                <div className="absolute flex justify-center items-center w-full -top-8 left-32 blur-md">
                  <img src="/images/shapes/shape-2.svg" alt="" className="" />
                </div>

                <div className="relative grid lg:grid-cols-4 gap-4">
                  <div className="flex gap-4">
                    <p className="2xl:text-xl font-gilroy font-semibold">
                      <Trans i18nKey={"contacts.title"}>Горячая линия</Trans>
                    </p>
                    <div className="w-full h-px bg-[#3D425C]"></div>
                  </div>

                  <div className="space-y-2 2xl:pr-4 xl:pr-2">
                    <a
                      href="mailto:info@graff.tech"
                      className="2xl:h-16 h-14 px-6 py-4 2xl:text-base text-sm border rounded-full font-medium flex justify-between items-center w-full border-[#52587A] opacity-80 hover:opacity-100 transition-all"
                    >
                      <span>
                        <Trans i18nKey={"contacts.button1"}>Написать</Trans>
                      </span>
                      <MailIcon className="lg:w-8 lg:h-8 w-6 h-6" />
                    </a>
                    <a
                      href="tel:88007700067"
                      className="2xl:h-16 h-14 px-6 py-4 2xl:text-base text-sm border rounded-full font-medium flex justify-between items-center w-full border-[#52587A] opacity-80 hover:opacity-100 transition-all"
                    >
                      <span>
                        <Trans i18nKey={"contacts.button2"}>Позвонить</Trans>
                      </span>
                      <PhoneIcon className="lg:w-8 lg:h-8 w-6 h-6" />
                    </a>
                  </div>

                  <div className="sm:col-span-2 flex sm:justify-end lg:mt-0 mt-10">
                    <div className="lg:w-auto sm:w-1/2 w-full flex justify-between 2xl:gap-8 lg:gap-6 gap-4">
                      <p className="2xl:text-xl font-gilroy font-semibold 2xl:-mt-1.5 -mt-1">
                        <Trans i18nKey={"contacts.social.title"}>
                          Социальные
                          <br />
                          сети
                        </Trans>
                      </p>
                      <div className="flex gap-2 h-fit">
                        <a
                          href="https://www.youtube.com/@GRAFFtech"
                          target="_blank"
                          className="group border border-[#3D425C] xl:p-4 p-3 rounded-full hover:border-[#52587A] transition-all"
                        >
                          <YouTubeIcon className="2xl:w-8 2xl:h-8 w-6 h-6" />
                        </a>
                        <a
                          href="https://vk.com/graff.interactive"
                          target="_blank"
                          className="group border border-[#3D425C] xl:p-4 p-3 rounded-full hover:border-[#52587A] transition-all"
                        >
                          <VKIcon className="2xl:w-8 2xl:h-8 w-6 h-6" />
                        </a>
                        <a
                          href="https://t.me/GRAFFinteractive"
                          target="_blank"
                          className="border rounded-full border-[#52587A] xl:p-4 p-3 opacity-80 hover:opacity-100 transition-all"
                        >
                          <TelegramIcon className="2xl:w-8 2xl:h-8 w-6 h-6" />
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="mt-[50px] relative border-t border-[#3D425C] text-sm">
              <div className="container mx-auto xl:px-8 max-w-[1600px]">
                <div className="grid lg:grid-cols-4">
                  <div className="sm:col-span-2 lg:order-none order-last py-6 xl:px-0 px-6 flex sm:flex-row flex-col sm:gap-6 gap-4 lg:border-t-0 border-t border-[#3D425C]">
                    <div>
                      <LogoIcon />
                    </div>
                    <div className="flex flex-col sm:gap-1 gap-4">
                      <p className="flex sm:flex-row flex-col sm:gap-4 gap-1">
                        <a
                          href="https://graff.tech/privacypolicy"
                          target="_blank"
                        >
                          <Trans i18nKey={"footer.link"}>
                            Политика конфиденциальности
                          </Trans>
                        </a>
                        <a href="https://graff.estate" target="_blank">
                          graff.estate
                        </a>
                      </p>
                      <p className="text-xs text-[#C5C7CE]">
                        © 2023 GRAFF interactive.{" "}
                        <Trans i18nKey={"footer.text"}>
                          Все права защищены.
                        </Trans>
                      </p>
                    </div>
                  </div>

                  <div className="col-span-1 lg:border-l sm:border-b-0 border-b border-[#3D425C] xl:px-8 sm:px-6 px-4 py-6 flex flex-col justify-center">
                    <div className="flex justify-between items-center">
                      <div className="text-[#EBEBEB] flex flex-col gap-1">
                        <a href="mailto:info@graff.tech">info@graff.tech</a>
                        <a href="tel:88007700067">8 800 770 00 67</a>
                      </div>
                      <div className="w-12 h-12 border border-[#3D425C] rounded-full flex justify-center items-center">
                        RU
                      </div>
                    </div>
                  </div>

                  <div className="col-span-1 sm:border-l border-[#3D425C] xl:pl-8 xl:pr-0 sm:px-6 px-4 py-6 flex flex-col justify-center">
                    <div className="flex justify-between items-center">
                      <div className="text-[#EBEBEB] flex flex-col gap-1">
                        <a href="mailto:waseem@graff.tech">waseem@graff.tech</a>
                        <a href="tel:+971509388902">+971 50 938 8902</a>
                      </div>
                      <div className="w-12 h-12 border border-[#3D425C] rounded-full flex justify-center items-center">
                        UAE
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <Transition in={isOpen} timeout={200} mountOnEnter unmountOnExit>
            {(state) => <Sidebar className={state} />}
          </Transition>

          <ToastContainer />
        </>
      ) : (
        <div className="bg-[#14161F] h-screen flex justify-center items-center">
          <p className="self-center text-white flex items-center gap-4 w-fit font-gilroy">
            <img
              src="/icons/Loader.png"
              alt=""
              className="animate-spin w-6 h-6"
            />
            <span>
              <Trans i18nKey="loading">Загрузка</Trans>
              ... {countdownTimer} <Trans i18nKey="loadingSub">сек</Trans>
            </span>
          </p>
        </div>
      )}
    </>
  );
}

export default App;
