// @ts-ignore
import { useEffect, useState } from "react"
import CommentSection from "components/comment/CommentSection"
import axios, { AxiosResponse } from "axios"
import Template from "components/window/Template"
import { fetch } from "logger"
import { GetStaticProps, NextPage } from 'next'
import toast from "react-hot-toast"
import { dehydrate, QueryClient } from "@tanstack/query-core"
import { useQuery } from "@tanstack/react-query"
import { Clan } from "helper/types"
import { useTracker } from "hooks/useTracker"
import Seo from "components/SEO"
import ClanWindow from "components/window/ClanWindow"
import { allowedToTrack } from "helper"

const ClanPage: NextPage<props> = ({
  id, error,
  isValid = false}: props) => {
    const {data:clan} = useQuery<Clan>([`clan-${id}`], async() => getClanData(id), {
    staleTime: 119000,
    cacheTime: 119000,
    refetchOnWindowFocus: true
    })
    const {getClanTrackerData, updateClanTrackerData} = useTracker()
    const [trackerData, setTrackerData] = useState({
      views: 0,
      badges: []
    })
    console.log(clan)
    useEffect(() => {
    ;(async() => {
      if(error) toast.error(error) 
      fetch.info({
      prefix: `Clan Page`,
      message: `Displaying Clan: %c${clan?.clan_name} (${id})%c\n\nValid: ${isValid}`
    })
    if(clan?.clan_id && clan.clan_name) {
      if(!allowedToTrack()) {
        setTrackerData(await getClanTrackerData(id, clan.clan_name))
        return
      }
      let viewed_before = localStorage.getItem(`clan_viewed_${id}`)
      let timestamp = viewed_before && JSON.parse(viewed_before)?.["timestamp"]
      // Check if the clan has been viewed before
      // and if it was viewed return
      // and check if current timestamp is greater than the timestamp
      if(viewed_before && timestamp && timestamp > Date.now()) {
        setTrackerData(await getClanTrackerData(id, clan.clan_name))
        return
      }
      setTrackerData(await updateClanTrackerData(id, clan.clan_name))
      localStorage.setItem(`clan_viewed_${id}`, JSON.stringify({
        timestamp: Date.now() + (4 * 60 * 60 * 1000)
      }))

    }
  })();
    return () => {

    }
  }, [])

  return (
    <>
      {/* @ts-ignore */}
      <Seo templateTitle={clan?.clan_name || "Clan Not Found"}
      description={clan?.clan_name ? `${clan?.clan_name} Stats on Brawlhalla` : "Clan not found"} />
      <Template useWindow
        mainWindowBig mainWindow={false}>

        <ClanWindow {...trackerData} {...clan} error={error}
        />
      </Template>
    </>
  )
}

// This is to cache the clan data for all requests
// And it re-fetches the clan data every 60s 
async function getClanData(id:string|number|string[]|undefined) {

  let clan: AxiosResponse = await axios.get<AxiosResponse>
  (`${process.env.DOMAIN}/api/clan/${id}`, {
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json",
    },
  });
  return clan.data
}
export const getStaticProps: GetStaticProps = async (context) => {
  let id = context?.params?.id
  if (!id) return {
    props: {
      isValid: false
    },
    revalidate: 120,
  }
  let isValid = false
 
  if (/[1-9]/g.test(id.toString()) && !isNaN(Number(id.toString())) && Number(id) >= 1) {
    isValid = true
  }
  if (id.length >= 18) {
    isValid = false
  }
  if (isValid) {
    try {
      const queryClient = new QueryClient()
      await queryClient.prefetchQuery([`clan-${id}`], async() => getClanData(id), {
        staleTime: 119000,
        cacheTime: 119000
        })
      return {
        props: {
          dehydratedState: dehydrate(queryClient),
          id,
          isValid
        },
        revalidate: 120,
      }

    } catch (e) {
      console.log(e)
      return {
        props: {
          error: !!e
        },
        revalidate: 120,
      }
    }
  }
  return {
    props: {
      id: id,
      isValid,
      error: "Invalid id"
    },
    // Re-fetches the data every {time} seconds
    revalidate: 120,
  }
}

export async function getStaticPaths() {
  return {
    paths: [],
    fallback: 'blocking'
  }
}

interface props {
  clan: clanData
  id: string | number
  error: any
  isValid?: boolean
}
export default ClanPage
