"use client"

import { LIST_FORUM, PAGINATION, wgnOptions } from "@/config/constant"
import { useGetGameForums } from "@/hook/useGames"
import { Link, usePathname } from "@/i18n/routing"
import { IGameForums, IGameMyPostQuery } from "@/type/Games"
import Image from "next/image"
import HeaderNewsPage from "../News/HeaderNewsPage"
import { useRecoilValue } from "recoil"
import { typeWGNState } from "@/recoil"
import { find, isEmpty, omitBy } from "lodash"
import { useCallback, useEffect, useMemo, useState } from "react"

import { useSearchParams } from "next/navigation"
import { useRouter } from "@/i18n/routing"
import { LoadingResult } from "../Common/LoadingResult/LoadingResult"
import HeaderBreadcrumb from "../Layout/HeaderBreadcrumb"
import SearchBox from "../Layout/SearchBox"
import { useTranslations } from "next-intl"

export default function ListForum() {
  const optionHeader = useRecoilValue<string | number>(typeWGNState)
  const options = wgnOptions()
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const oldSearch = Object.fromEntries(searchParams.entries())
  const defaultQ = { pageNum: 1, pageSize: 25 }
  const trans = useTranslations("wgn")
  const [keyword, setKeyword] = useState(searchParams.get("search") || "")

  const [page, setPage] = useState(PAGINATION.DEFAULT_CURRENT_PAGE)
  const [totalPage, setTotalPage] = useState(0)
  const defaultQuery = {
    pageNum: page,
    pageSize: PAGINATION.DEFAULT_PAGE_SIZE,
  }
  const [query, setQuery] = useState<IGameMyPostQuery>(defaultQuery)

  const { data: gameForums, isLoading } = useGetGameForums(query)

  useEffect(() => {
    handleSearchKeyword(searchParams.get("search") || "")
    setKeyword(searchParams.get("search") || "")
  }, [searchParams])

  const dataGameForums = useMemo(() => {
    const arrGameForums = new Map(gameForums?.data?.data?.forums?.map((item: IGameForums) => [item.id, item]))

    const mergedArrayForum = !isEmpty(arrGameForums)
      ? LIST_FORUM.map((item) => ({
          ...item,
          ...arrGameForums.get(item.id),
        }))
      : []

    return mergedArrayForum
  }, [gameForums?.data?.data?.forums])

  useEffect(() => {
    if (!isEmpty(Object.fromEntries(searchParams.entries()))) {
      const updatedQuery = { ...oldSearch } as IGameMyPostQuery
      setQuery(updatedQuery)
      updateSearchQuery(updatedQuery)

      if (searchParams.has("search")) {
        handleSearchKeyword(oldSearch?.search)
      }
    }
  }, [])

  const updateSearchQuery = useCallback(
    (updatedQuery: any) => {
      const params = new URLSearchParams(searchParams)

      Object.entries(updatedQuery).forEach(([key, value]) => {
        value ? params.set(key, String(value)) : params.delete(key)
      })

      Array.from(params.keys()).forEach((key) => {
        if (!(key in updatedQuery)) {
          params.delete(key)
        }
      })

      router.push(`?${params.toString()}`, { scroll: false })
    },
    [searchParams, pathname, query],
  )

  const handleSearchKeyword = (keyword: string) => {
    if (keyword && keyword?.length >= 3) {
      const updatedQuery = { ...defaultQ, ...oldSearch, search: keyword?.trim() }
      const cleanedObj = omitBy(updatedQuery, (value) => value === null || value === undefined || value === "")

      setQuery(cleanedObj)
      updateSearchQuery(cleanedObj)
    }
    if (keyword === "" && query?.search) {
      setPage(1)
      setQuery(defaultQ)
      updateSearchQuery(defaultQ)
    }
  }

  const handleScroll = (e: any) => {
    const { scrollTop, scrollHeight, clientHeight } = e.target
    if (scrollTop + clientHeight >= scrollHeight - 5) {
      if (page < totalPage && !isLoading) {
        setPage(page + 1)
        setQuery({ ...query, pageSize: PAGINATION.DEFAULT_PAGE_SIZE, pageNum: page + 1 })
      }
    }
  }

  useEffect(() => {
    const mainElement = document.getElementById("layout-list-forums")

    const handleScroll = () => {
      if (mainElement) {
        const { scrollTop, scrollHeight, clientHeight } = mainElement
        if (scrollTop + clientHeight >= scrollHeight - 5) {
          if (page < totalPage && !isLoading) {
            setPage(page + 1)
            setQuery({ ...query, pageSize: PAGINATION.DEFAULT_PAGE_SIZE, pageNum: page + 1 })
          }
        }
      }
    }

    if (mainElement) {
      mainElement.addEventListener("scroll", handleScroll)
    }

    return () => {
      if (mainElement) {
        mainElement.removeEventListener("scroll", handleScroll)
      }
    }
  }, [])

  return (
    <>
      {/* <HeaderNewsPage
        title={find(options, { value: optionHeader as string })?.label || ""}
        onSearch={handleSearchKeyword}
        filter={false}
        keyTransPlaceholder="wgn"
        placeholder="search_forum_here"
      /> */}
      <HeaderBreadcrumb
        showButton={false}
        items={[
          {
            aria_label: find(options, { value: optionHeader as string })?.label || "",
            href: "#",
            title: find(options, { value: optionHeader as string })?.label || "",
          },
        ]}
        className="flex-col !items-start lg:flex-row lg:items-center"
        slot={
          <SearchBox
            value={keyword}
            onSearch={handleSearchKeyword}
            onChange={setKeyword}
            placeholder={trans("search_forum_here")}
            className="h-12"
            classInput="!h-12 lg:!w-56 xl:!w-56"
            classButton="!h-12 md:!pl-2"
          />
        }
      />
      <LoadingResult
        isLoading={isLoading && !dataGameForums?.length}
        isShowResult={Boolean(dataGameForums?.length)}
        icon="/img/gif/WGN.gif"
        result={
          <div
            onScroll={handleScroll}
            id="layout-list-forums"
            className="py-6 px-4 grow overflow-y-auto">
            <ul className="gap-2 md:gap-4 grid md:grid-cols-2">
              {dataGameForums.map((item, index) => (
                <li
                  key={index}
                  className="relative rounded-2xl overflow-hidden">
                  <Link
                    href={`/wgn/${item.id}`}
                    className="absolute top-0 left-0 w-full h-full"></Link>
                  <Image
                    alt={item.name}
                    src={item.thumbnail}
                    width={533}
                    height={220}
                    style={{ width: "100%", height: "100%" }}
                    className="object-cover rounded-2xl"
                  />
                  <p className="absolute bottom-0 left-0 z-10 pb-4 w-full text-center font-bold text-white text-lg md:text-xl lg:text-2xl">{item.name}</p>
                </li>
              ))}
            </ul>
          </div>
        }
      />
    </>
  )
}
