"use client"

import { Avatar, Button, Form, Modal } from "antd"
import { Dispatch, SetStateAction, forwardRef, useImperativeHandle, useState } from "react"
import { useTranslations } from "next-intl"
import TextArea from "antd/es/input/TextArea"
import { useQueryClient } from "@tanstack/react-query"
import classNames from "classnames"
import { customFormCommentCss } from "./style"
import { IChildrenGameComments } from "@/type/Games"
import { isEmpty } from "lodash"
import { useCreatePostComment } from "@/hook/useGames"
import { useNotificationContext } from "@/component/Layout/NotificationContext"

type IProps = {
  setReplyTo: Dispatch<SetStateAction<IChildrenGameComments>>
  reolyTo?: IChildrenGameComments
  postid: string
}

export const FromComment = forwardRef(({ reolyTo, setReplyTo, postid }: IProps, ref) => {
  const [formRef] = Form.useForm()
  const queryClient = useQueryClient()
  const { notify } = useNotificationContext()

  const trans = useTranslations("wgn")
  const tranButton = useTranslations("button")
  const transGeneral = useTranslations("general")
  const transMessage = useTranslations("message")

  const [isModalOpen, setIsModalOpen] = useState(false)

  const dataProfile: any = queryClient.getQueryData(["auth.profile"])
  const createPostComment = useCreatePostComment()

  const handleCancel = () => {
    setIsModalOpen(false)
    setReplyTo({})
    formRef.resetFields()
  }

  useImperativeHandle(ref, () => ({
    showModal: () => {
      setIsModalOpen(true)
    },

    handleCancel,
  }))

  const onFinish = (values: any) => {
    const dataRq = {
      parent_id: !isEmpty(reolyTo) ? Number(reolyTo?.id) : 0,
      content: values?.content || "",
    }

    createPostComment
      .mutateAsync({ id: postid, data: dataRq })
      .then(() => {
        handleCancel()
        notify({
          type: "success",
          message: transMessage("congratulation"),
          description: transGeneral("comment_successful"),
        })
        queryClient.invalidateQueries({ queryKey: ["games.get_list_comment_by_id", Number(postid)] })
      })
      .catch((error) => {
        let concatenatedMsgs = ""
        if ([401, 404].includes(error?.status)) {
          concatenatedMsgs = error?.response?.data.msgs ? error?.response?.data.msgs : transMessage("fail")
        } else if (error?.status === 400) {
          concatenatedMsgs = error?.response?.data.msgs ? Object.values(error?.response?.data.msgs).join("<br />") : transMessage("fail")
        }

        notify({
          type: "error",
          message: transMessage("something_wrong"),
          description: concatenatedMsgs,
        })
      })
  }

  return (
    <>
      <Modal
        destroyOnClose
        maskClosable={false}
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}>
        <Form
          className={classNames(customFormCommentCss)}
          name="add_comment_post_wgn"
          form={formRef}
          onFinish={onFinish}
          autoComplete="off"
          colon={false}
          layout="horizontal">
          <div className="mb-4">
            <div className="text-2xl leading-[30px] text-[var(--secondary-100)] text-left mb-4">
              {!isEmpty(reolyTo) ? (
                <>
                  {transGeneral("reply_comment")}{" "}
                  <Avatar
                    shape="square"
                    size={64}
                    src={reolyTo?.user?.photo || "/img/account/avatar.svg"}
                  />{" "}
                  {reolyTo?.user?.username || ""}
                </>
              ) : (
                trans("post_comment")
              )}
            </div>
            <hr />
          </div>
          <Form.Item
            label={
              <Avatar
                shape="square"
                size={64}
                src={dataProfile?.data?.photo || "/img/account/avatar.svg"}
              />
            }
            name="content"
            rules={[
              { required: true, message: transGeneral("pl_leave_your_comment_here") },
              { min: 5, message: transGeneral("content_must_num", { num: 5 }) },
            ]}>
            <TextArea
              rows={4}
              placeholder={transGeneral("pl_leave_your_comment_here")}
              size="large"
              onBlur={(e) => {
                formRef.setFieldsValue({
                  content: e.target.value.trim(),
                })
              }}
            />
          </Form.Item>

          <div className="pt-4 flex justify-end ml-auto gap-2 w-full md:w-1/2">
            <Button
              onClick={handleCancel}
              className="w-full md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 xl:!h-16 !rounded-lg !border-[var(--secondary-20)] !bg-[var(--secondary-10)]"
              loading={createPostComment?.isPending}>
              {tranButton("cancel")}
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              className="w-full md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 xl:!h-16 !rounded-lg"
              loading={createPostComment?.isPending}>
              {tranButton("submit")}
            </Button>
          </div>
        </Form>
      </Modal>
    </>
  )
})
