"use client"

import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { find, isEmpty, omit, omitBy } from "lodash"
import { useTranslations } from "next-intl"
import CardItemAllForumsWGN from "./ItemAllForumWGN"
import HeaderBreadcrumb from "@/component/Layout/HeaderBreadcrumb"
import { Link, usePathname, useRouter } from "@/i18n/routing"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { LIST_FORUM, PAGINATION, wgnOptions } from "@/config/constant"
import { typeWGNState } from "@/recoil"
import { useRecoilValue } from "recoil"
import { faPlus } from "@fortawesome/free-solid-svg-icons"
import dayjs from "dayjs"
import CustomDropdownView from "@/component/Common/SelectView"
import SearchBox from "@/component/Layout/SearchBox"
import { useParams } from "next/navigation"
import { useGetDetailGameForums } from "@/hook/useGames"

import { useSearchParams } from "next/navigation"
import advancedFormat from "dayjs/plugin/advancedFormat"
import utc from "dayjs/plugin/utc"
import timezone from "dayjs/plugin/timezone"
import { LoadingResult } from "@/component/Common/LoadingResult/LoadingResult"
import { IDetailGameForumsQuery, IMyGamePost } from "@/type/Games"
import { Button } from "antd"
import { DatePickerCustom } from "@/component/Common/DatePickerCustom"

dayjs.extend(advancedFormat)
dayjs.extend(utc)
dayjs.extend(timezone)

const AllForumsWGN = () => {
  const { forumid: id } = useParams()
  const router = useRouter()
  const trans = useTranslations("wgn")
  const transButton = useTranslations("button")
  const options = wgnOptions()
  const typeWGN = useRecoilValue(typeWGNState)
  const [searchValue, setSearchValue] = useState("")
  const [selectedSort, setSelectedSort] = useState("no_sort")
  const [tempSort, setTempSort] = useState(selectedSort)

  const pathname = usePathname()
  const searchParams = useSearchParams()
  const oldSearch = Object.fromEntries(searchParams.entries())
  const defaultQ = { pageNum: 1, pageSize: 25 }

  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<IDetailGameForumsQuery>(defaultQuery)

  const { data: detailGameForums, isLoading } = useGetDetailGameForums(id as string, Boolean(id), query)

  const datePickerRef = useRef<null | { updateDatePicker: (start: number, end: number) => void }>(null)

  const dataGamePosts = useMemo(() => {
    setTotalPage(detailGameForums?.data?.data?.total_pages || 0)

    return detailGameForums?.data?.data?.posts
  }, [detailGameForums?.data?.data?.posts, detailGameForums?.data?.data?.total_pages])

  const countData = useMemo(() => dataGamePosts?.length || 0, [dataGamePosts?.length])

  const handleFilterSortBy = (value: string) => {
    const updatedQuery = { ...oldSearch, sortBy: value === "no_sort" ? "" : value } as IDetailGameForumsQuery
    const cleanedObj = omitBy(updatedQuery, (value) => value === null || value === undefined || value === "")
    setQuery(cleanedObj)
    updateSearchQuery(cleanedObj)
  }

  const handleClearFilter = () => {
    const arrKey = Array.from(searchParams.keys())
    const removeKey = omit(oldSearch, arrKey || []) as IDetailGameForumsQuery

    setSearchValue("")
    setSelectedSort("no_sort")
    datePickerRef.current?.updateDatePicker(0, 0)

    setQuery(removeKey)
    updateSearchQuery(removeKey)
  }

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

      if (Object.keys(updatedQuery).length === 0) {
        router.push(pathname, { scroll: false })
      } else {
        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) {
      const updatedQuery = { ...defaultQ, ...oldSearch, search: "" }
      const cleanedObj = omitBy(updatedQuery, (value) => value === null || value === undefined || value === "")
      setQuery(cleanedObj)
      updateSearchQuery(cleanedObj)
    }
  }

  const wgnCurrent = useMemo(() => {
    return find(LIST_FORUM, { id: `${id}` })?.name
  }, [id])

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

      if (searchParams.has("startDate") && searchParams.has("endDate")) {
        datePickerRef.current?.updateDatePicker(Number(oldSearch?.startDate), Number(oldSearch?.endDate))
      }
      if (searchParams.has("search")) {
        setSearchValue(oldSearch?.search)
      }
      if (searchParams.has("sortBy")) {
        setSelectedSort(oldSearch?.sortBy)
      }
    }
  }, [])

  const handleDateChange = (start: number, end: number) => {
    if (start && end) {
      const updatedQuery = { startDate: start, endDate: end }
      setQuery(updatedQuery)
      updateSearchQuery(updatedQuery)
    }
  }

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

  useEffect(() => {
    const mainElement = document.getElementById("list-forum-game-posts")

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

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

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

  return (
    <div className="h-full flex flex-col">
      <HeaderBreadcrumb
        items={[
          {
            aria_label: find(options, { value: typeWGN as string })?.label || "",
            href: "/wgn",
            title: find(options, { value: typeWGN as string })?.label || "",
          },
          {
            aria_label: `${wgnCurrent}`,
            href: `/wgn/${id}`,
            title: `${wgnCurrent}`,
          },
        ]}
        className="flex-col !items-start lg:flex-row lg:items-center"
        slot={
          <div className="flex gap-2 items-center mt-2 lg:mt-0">
            <SearchBox
              value={searchValue}
              onSearch={handleSearchKeyword}
              onChange={setSearchValue}
              placeholder={trans("search_question_here")}
              className="h-12"
              classInput="!h-12 lg:!w-56 xl:!w-56"
              classButton="!h-12 md:!pl-2"
            />
            <Link
              aria-label="post question"
              href={`/wgn/post-question?type=${id}`}
              className="rounded-lg border border-solid border-[var(--primary--70)] px-4 py-3 font-bold bg-[var(--primary--70)] !text-white text-base hover:opacity-80 whitespace-nowrap">
              <FontAwesomeIcon icon={faPlus} />
              {` ${trans("post_question")}`}
            </Link>
          </div>
        }
      />
      <div className="pt-6 px-5 flex flex-col sm:flex-row gap-4">
        <DatePickerCustom
          ref={datePickerRef}
          onDateChange={handleDateChange}
        />

        <CustomDropdownView
          selectedSort={selectedSort}
          setSelectedSort={setSelectedSort}
          tempSort={tempSort}
          setTempSort={setTempSort}
          handleFilterSortBy={handleFilterSortBy}
        />
        <Button
          className="!h-auto self-start sm:self-auto"
          type="primary"
          onClick={() => {
            handleClearFilter()
          }}>
          {transButton("clear_filter")}
        </Button>
      </div>

      <LoadingResult
        isLoading={isLoading && !dataGamePosts?.length}
        isShowResult={Boolean(dataGamePosts?.length)}
        icon="/img/gif/WGN.gif"
        result={
          <>
            <div className="px-5 pt-6 pb-2">{`${trans("you_have")} ${countData || 0} ${countData > 1 ? trans("posts") : trans("post")}`}</div>
            <div
              onScroll={handleScroll}
              id="list-forum-game-posts"
              className="overflow-y-auto">
              <div className="grid grid-cols-1 gap-2 p-4">
                {dataGamePosts?.map((item: IMyGamePost) => (
                  <CardItemAllForumsWGN
                    key={item?.id}
                    keyProps={item?.id}
                    className="col-span-1 flex"
                    type={"me"}
                    url={`/wgn/detail/${item?.id}`}
                    url_image={item?.thumbnail}
                    alt_image={item?.bannerimage_org}
                    classNameImage="rounded-lg"
                    title={item?.title}
                    decs={item?.content}
                    date={dayjs.unix(Number(item?.created)).format("ddd, MMM DD, YYYY")}
                    time={dayjs.unix(Number(item?.created)).format("HH:mm")}
                    numberView={item?.views}
                    numberReplied={item?.replied}
                  />
                ))}
              </div>
            </div>
          </>
        }
      />
    </div>
  )
}

export default AllForumsWGN
