import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import Button from "components/Button";
import Seo from "components/SEO";
import Logo from "components/SVGs/Logo";
import Template from "components/window/Template";
import { useMediaQuery } from "hooks/useMediaQuery";
import { NextPage } from "next";
import { BsFillPersonFill } from "react-icons/bs";
import {motion} from "framer-motion"
import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/router";
const Home: NextPage = () => {
  const router = useRouter()
  const [inputContent, setInputContent] = useState("")
  const searchRef = useRef<HTMLInputElement>(null);
  const submitRef = useRef<HTMLButtonElement>(null);
  const isSmall = useMediaQuery({ maxWidth: "550px" });
  const { data } = useQuery(
    ["website-info"],
    async () => {
      return (
        await axios.get(`${process.env.DOMAIN}/api/tracker/views`, {
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
          },
        })
      ).data;
    },
    {
      staleTime: 12000,
      cacheTime: 12000,
    }
  );
  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);

    // Clean up the event listener when the component unmounts
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, []);

  return (
    <>
      <Seo templateTitle="Home" />
      <Template>
        <motion.div  layoutId="headerContainer">
        <motion.div className="flex items-center justify-center" transition={{
          repeat: Infinity, 
          repeatType: "reverse",
          duration: 2
        }} animate={{
          y: 10
        }}>
        <motion.div transition={{
          duration: 1.5,
        }} 
        >
        <Logo size={isSmall ? 16 : 32} />
        </motion.div>
        </motion.div>
        <div className={`flex gap-2 ${isSmall ? "flex-col gap-4 items-center" : "flex-row"}`}>
          <motion.div transition={{
            duration: 0.3,
          }} 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.3,
            }}
              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 -mt-[0.1rem]" />
          </motion.div>
          <motion.div layoutId="SearchButton" transition={{
            duration: 0.3,
          }}>
          <Button ref={submitRef} onClick={() => {
            router.push("/search/"+inputContent+"?animate=true", "/search/"+inputContent)
          }} disabled={inputContent.length < 4}
            style={{
              marginTop: "-0.35rem",
            }}
          >
            Search
          </Button>
          </motion.div>
        </div>
        </motion.div>
      </Template>
    </>
  );
};

export default Home;
