// Importing Styles and packages
import "styles/globals.css";
import NavBar from "components/NavBar";
import toast, { Toaster } from "react-hot-toast";
// @ts-ignore
import { useEffect, useRef, useState } from "react";
// import twemoji from "twemoji"
import Image from "next/image";
import { NextPage } from "next";
import { AppProps } from "next/app";
import { useRouter } from "next/router";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { Hydrate } from "@tanstack/react-query";
import Link from "next/link";
import { SessionProvider } from "next-auth/react";
import { motion, AnimatePresence } from "framer-motion";
// @ts-ignore
import React from "react";
import { getCookie, setCookie } from "cookies-next";
import { useTracker } from "hooks/useTracker";
import { Session } from "next-auth";
import NavBarBG from "components/SVGs/NavBarBG";
import Logo from "components/SVGs/Logo";
import { BsFillPersonFill } from "react-icons/bs";
import Button from "components/Button";
import backgroundPic from "../../public/assets/background.jpg";
import { useMediaQuery } from "hooks/useMediaQuery";

// import { AiOutlineClose } from 'react-icons/ai'
// import useEasterEgg from 'hooks/useEasterEgg'
// import Backdrop from 'components/Backdrop'
// import Modal from 'components/Modal'
// const { description, theme_color, name } = require("../../public/manifest.json")
const _app: NextPage<
  props & {
    dehydratedState: any;
  }
> = ({ Component, pageProps }: props) => {
  const router = useRouter();
  const searchRef = useRef<HTMLInputElement>(null);
  const submitRef = useRef<HTMLButtonElement>(null);
  const [inputContent, setInputContent] = useState("")
  const [hideArticles, setHideArticles] = useState(false);
  const [queryClient] = useState(() => new QueryClient());
  const { increaseVisits } = useTracker();
  const isSmall = useMediaQuery({ maxWidth: "800px" });
  const isSmaller = useMediaQuery({ maxWidth: "550px" });
  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      if (event.key === '/') {
        event.preventDefault(); // Prevent default '/' behavior (e.g., focus address bar)
        searchRef.current?.focus();
        console.log(submitRef.current)

      }
      if((event.key === "Enter" || event.key === "NumpadEnter") && !submitRef.current?.disabled) {
        event.preventDefault()
        console.log(submitRef.current)
        submitRef.current?.click();
      }
    };

    document.addEventListener('keydown', handleKeyPress);

    if (localStorage.getItem("hideArticles") === "yes") {
      setHideArticles(true);
    }
    if (getCookie("firstVisit") !== "no") {
      // Increase views
      increaseVisits(!getCookie("firstVisit"));
      setCookie("firstVisit", "no", { expires: new Date(2140483642222) });
    } else {
      increaseVisits(!getCookie("firstVisit"));
    }
    if (window.matchMedia("(display-mode: standalone)").matches) return;
    // Listen to appinstalled, when app is installed remove the event
    const onInstall = () => {
      toast.success("Thank you for installing the application!");
    };
    window.addEventListener("appinstalled", onInstall);
    return () => {
      document.removeEventListener('keydown', handleKeyPress);

      window.removeEventListener("appinstalled", onInstall);
    };
  }, []);
  useEffect(() => {
    setInputContent(router.query?.["name"] || "")
  }, [router.asPath])
  
  return router.asPath !== "/surprise" ? (
    <QueryClientProvider client={queryClient}>
      {/* @ts-ignore */}
      <Hydrate state={pageProps?.dehydratedState}>
        <noscript>
          <button
            style={{
              width: "100vw",
              cursor: "pointer",
              height: "5rem",
              position: "fixed",
              zIndex: "99999999999",
              fontFamily: "Coda",
              paddingTop: "0rem",
              textAlign: "center",
              backgroundColor: "rgb(254 109 115)",
              color: "rgb(255 251 244)",
              fontSize: "2rem",
            }}
          >
            Please enable javascript for a usable experience.
          </button>
        </noscript>
        <meta name="robots" content="noindex" />
        <AnimatePresence exitBeforeEnter>

        <main>
          {/* <div className='backdrop' /> */}
          <Toaster
            position="top-center"
            reverseOrder={false}
            toastOptions={{
              duration: 5000,
              style: {
                borderRadius: "10px",
                // background: '#333',
                // color: '#fff',
                zIndex: 99999,
              },
              className: "toast",
            }}
          />
          <>
            <div className="bg">
              <Image
                priority
                alt="Background Image"
                src={backgroundPic}
                layout="fill"
                placeholder="blur"
                quality={100}
                sizes="100vw"
                style={{
                  objectFit: "cover",
                }}
              />
            </div>
            <div className="navbar_wrapper w-full mb-16">
              <NavBar router={router} />
              <br />
            </div>
            {router.asPath !== "/" ? (
              <motion.div className={`flex justify-center -mt-3 items-center gap-2 ${isSmall ? "flex-col" : "flex-row"}`}>
                <motion.div
                  className="-mt-6"
                  transition={{
                    duration: 1.5,
                  }}
                >
                  <Logo size={isSmaller ? 16 : 12} />
                </motion.div>
                <div className={`flex gap-2 ${isSmaller ? "flex-col gap-4 items-center" : "flex-row"}`}>
                  <motion.div
                    transition={{
                      duration: 0.4,
                    }}
                    layoutId="SearchContainer"
                    className="relative flex items-center  flex-row w-80 h-11 bg-common-white rounded-md"
                  >
                     <motion.input ref={searchRef} onChange={(e) => {
              let v = e.target.value
              if(v.length > 32 || v.includes("\\") || v.includes("/")) return
              setInputContent(v)
            }} value={inputContent} layoutId="SearchInput" transition={{
              duration: 0.4
            }}
              className="w-[88%] p-3 h-10 bg-transparent  text-xl font-LuckiestGuy text-common-black placeholder-[#C8C8C8]"
              placeholder="Player Name..."
            />
                    <BsFillPersonFill size={"2rem"} className="text-primary" />
                  </motion.div>
                  <motion.div
                    layoutId="SearchButton"
                    transition={{
                      duration: 0.4,
                    }}
                  >
                    <Button ref={submitRef} onClick={() => {
            router.push("/search/"+inputContent, "/search/"+inputContent)
          }} disabled={inputContent.length < 4}
            style={{
              marginTop: "-0.35rem",
            }}
          >
            Search
          </Button>
                  </motion.div>
                </div>
              </motion.div>
            ) : null}
            <SessionProvider session={pageProps?.session}>
              {router.asPath !== "/" ? 
              <AnimatePresence exitBeforeEnter>
                <motion.div initial={true ? {
        y: 20,
        opacity: 0
      } : {}} animate={true ? {
        y: 0,
        opacity: 1
      } : {}} exit={{
        y: -20,
        opacity: 0,
      }} transition={{
        duration: 0.3,
        delay: 0.4
      }}>
              <Component router={router} {...pageProps} key={router.asPath} />
              </motion.div>
              </AnimatePresence> : <Component router={router} {...pageProps} key={router.asPath} />}
            </SessionProvider>

            {/* <div className='text-center
            bg-red-600 font-Coda font-bold
             w-auto h-auto bottom-6 fixed'>
                IN EARLY DEVELOPMENT
              </div> */}
          </>
        </main>
        </AnimatePresence>
        <NavBarBG style={{ zIndex: "-1", transform: "rotate(180deg)", position: "absolute", 
            minHeight: "10vh",
            maxWidth: "500vw"

          
        }} />

        <div className="h-[10vh] pt-6 flex text-center items-center justify-center">
          <h1 className="font-Coda text-2xl text-common-black">StatHalla | 2025</h1>

        </div>
      </Hydrate>
      <ReactQueryDevtools position="bottom-right" initialIsOpen={false} />
    </QueryClientProvider>
  ) : (
    <Component router={router} {...pageProps} key={router.asPath} />
  );
};

type props = AppProps & {
  dehydratedState: any;
  pageProps: {
    session: Session;
  };
};

export default _app;
