"use client"

import { useGetPostCommentList } from "@/hook/useGames"
import { IChildrenGameComments } from "@/type/Games"
import { Avatar, Button, List } from "antd"
import classNames from "classnames"
import { flattenDeep } from "lodash"
import { useParams } from "next/navigation"
import { forwardRef, useEffect, useMemo, useState } from "react"
import { listCommentCss } from "./style"
import dayjs from "dayjs"
import Image from "next/image"
import { useTranslations } from "next-intl"
import { LoadingResult } from "@/component/Common/LoadingResult/LoadingResult"
import { FromComment } from "./FromComment"
import { LoadMoreInfinite } from "@/component/Common/LoadMoreInfinite"

type IRef = { showModal: () => void }

export const CommentList = forwardRef<IRef, {}>((props, ref) => {
  const { postid } = useParams()

  const transGeneral = useTranslations("general")

  const [isNextPage, setIsNextPage] = useState(true)
  const [replyTo, setReplyTo] = useState<IChildrenGameComments>({})
  const [expandedItems, setExpandedItems] = useState<any>({})

  const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetPostCommentList(Number(postid), Boolean(postid))

  const commentsTree = (comments: IChildrenGameComments[], parentId = "0") => {
    let tree: IChildrenGameComments[] = []

    comments
      .filter((comment) => comment?.parent_id === parentId)
      .forEach((comment) => {
        let children = commentsTree(comments, comment.id)
        if (children.length) {
          comment.children = children
        }
        tree.push(comment)
      })

    return tree
  }

  const dataComments = useMemo(
    () => (flattenDeep(data?.pages.map((e: any) => e.data!)).length > 0 ? commentsTree(flattenDeep(data?.pages.map((e: any) => e?.data?.data?.comments))) : []),
    [data?.pages],
  )

  useEffect(() => {
    if (Number(data?.pageParams?.at(-1)) >= Number(data?.pages?.at(-1)?.data?.data?.total_pages)) {
      setIsNextPage(false)
    }
    if (!isNextPage && Number(data?.pageParams?.at(-1)) < Number(data?.pages?.at(-1)?.data?.data?.total_pages)) {
      setIsNextPage(true)
    }
  }, [isNextPage, data?.pages, data?.pageParams])

  const toggleExpand = (itemKey: string) => {
    setExpandedItems((prev: any) => ({
      ...prev,
      [itemKey]: !prev[itemKey],
    }))
  }

  return (
    <div className={classNames(listCommentCss)}>
      <LoadingResult
        isLoading={isLoading && !dataComments?.length}
        isShowResult={Boolean(dataComments?.length)}
        contentNotFound={<p className="md:text-base lg:text-lg">{transGeneral("no_comment_yet")}</p>}
        result={
          <List
            loading={isFetchingNextPage}
            itemLayout="horizontal"
            dataSource={dataComments}
            renderItem={(item: IChildrenGameComments) => {
              const isExpanded = (item?.id && expandedItems[item.id]) || false
              const displayedData = isExpanded && item.children ? item.children : item?.children?.slice(0, 1)

              return (
                <List.Item className="bg-white !p-4 mb-2 rounded-[10px] border border-[var(--secondary-10)]">
                  <List.Item.Meta
                    avatar={
                      <Avatar
                        shape="square"
                        size={64}
                        src={item?.user?.photo || "/img/account/avatar.svg"}
                      />
                    }
                    title={
                      <div className="flex justify-between mb-3">
                        <span className="text-sm font-semibold text-[var(--secondary-80)]">{item?.user?.username || "--"}</span>{" "}
                        <span className="font-normal text-xs text-[var(--secondary-80)]">{dayjs.unix(Number(item?.created)).format("MMM DD, YYYY")}</span>
                      </div>
                    }
                    description={
                      <>
                        <p
                          className="font-normal text-xs text-[var(--secondary-80)] mb-4"
                          dangerouslySetInnerHTML={{ __html: item?.content || "" }}></p>

                        <Button
                          className="mt-2 !bg-[var(--secondary-100)] hover:!bg-[var(--secondary-70)]"
                          onClick={() => {
                            setReplyTo(item), (ref as React.RefObject<IRef>)?.current?.showModal()
                          }}
                          type="primary">
                          <Image
                            src="/img/icon/chatbox_white.svg"
                            alt="message"
                            width={24}
                            height={24}
                            className="group-hover:hidden"
                          />
                          {transGeneral("reply")}
                        </Button>
                        {item?.children?.length && item?.children?.length > 0 && (
                          <List
                            itemLayout="horizontal"
                            dataSource={displayedData}
                            renderItem={(reply, index) => {
                              return (
                                <>
                                  <List.Item className="bg-white !py-1 !pr-1 mt-4 rounded-[10px] border border-[var(--secondary-10)]">
                                    <List.Item.Meta
                                      avatar={
                                        <Avatar
                                          shape="square"
                                          size={64}
                                          src={reply?.user?.photo || "/img/account/avatar.svg"}
                                        />
                                      }
                                      title={
                                        <div className="flex justify-between mb-3">
                                          <span className="text-sm font-semibold text-[var(--secondary-80)]">{reply?.user?.username || "--"}</span>{" "}
                                          <span className="font-normal text-xs text-[var(--secondary-80)]">
                                            {dayjs.unix(Number(reply?.created)).format("MMM DD, YYYY")}
                                          </span>
                                        </div>
                                      }
                                      description={
                                        <p
                                          className="font-normal text-xs text-[var(--secondary-80)]"
                                          dangerouslySetInnerHTML={{ __html: reply?.content || "" }}></p>
                                      }
                                    />
                                  </List.Item>

                                  {item?.children?.length && item?.children?.length > 1 && index === 0
                                    ? !isExpanded && (
                                        <Button
                                          type="link"
                                          className="mt-2 text-[var(--secondary-80)]"
                                          onClick={() => item?.id && toggleExpand(item.id)}>
                                          {transGeneral("see_more")}
                                        </Button>
                                      )
                                    : isExpanded &&
                                      item?.children?.length &&
                                      item?.children?.length - 1 === index && (
                                        <Button
                                          type="link"
                                          className="mt-2 text-[var(--secondary-80)]"
                                          onClick={() => item?.id && toggleExpand(item.id)}>
                                          {transGeneral("hide")}
                                        </Button>
                                      )}
                                </>
                              )
                            }}
                          />
                        )}
                      </>
                    }
                  />
                </List.Item>
              )
            }}
          />
        }
      />
      <LoadMoreInfinite
        isLoading={isLoading}
        isNextPage={isNextPage}
        hasNextPage={hasNextPage}
        fetchNextPage={fetchNextPage}
      />

      <FromComment
        reolyTo={replyTo}
        setReplyTo={setReplyTo}
        postid={postid as string}
        ref={ref}
      />
    </div>
  )
})
