"use client"

import { Button, Form, Modal } from "antd"
import { forwardRef, useImperativeHandle, useState } from "react"
import Rate from "@component/Common/Rate"
import { useTranslations } from "next-intl"
import TextArea from "antd/es/input/TextArea"
import { useNotificationContext } from "@/component/Layout/NotificationContext"
import { useRouter } from "next/navigation"
import { useAddCommentMarket } from "@/hook/useMarket"

interface IProps {
  startSize: number
  postid: number
}

export const FromMarketComment = forwardRef(({ startSize, postid }: IProps, ref) => {
  const [formRef] = Form.useForm()
  const { notify } = useNotificationContext()
  const router = useRouter()

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

  const [isModalOpen, setIsModalOpen] = useState(false)

  const createPostComment = useAddCommentMarket()

  const handleCancel = () => {
    setIsModalOpen(false)
  }

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

    handleCancel,
  }))

  const onFinish = (values: any) => {
    const dataRq = {
      rating: values?.rate,
      comment: values?.comment || "",
    }

    createPostComment
      .mutateAsync({ id: postid, body: dataRq })
      .then(() => {
        handleCancel()
        notify({
          type: "success",
          message: transMessage("congratulation"),
          description: transGeneral("comment_successful"),
        })
        router.refresh()
      })
      .catch((error) => {
        let concatenatedMsgs = ""
        if (typeof error?.response?.data.msgs === "string") {
          concatenatedMsgs = error?.response?.data.msgs ? error?.response?.data.msgs : transMessage("fail")
        } else {
          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
        // closable={false}
        maskClosable={false}
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}>
        <Form
          name="add_kuisine"
          form={formRef}
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical">
          <div>
            <p className="text-2xl leading-[30px] text-[var(--secondary-100)] text-center">{transGeneral("leave_your_rating_comment")}</p>
            <hr className="my-6" />

            <Form.Item
              label={transGeneral("pl_swipe_the_star_to_rate")}
              name="rate"
              rules={[{ required: true, message: transGeneral("pl_swipe_the_star_to_rate") }]}>
              <Rate
                value={0}
                interactive={true}
                size={startSize}
              />
            </Form.Item>
          </div>
          <Form.Item
            label={transGeneral("leave_your_comment_here")}
            name="comment"
            rules={[
              { required: true, message: transGeneral("pl_leave_your_comment_here") },
              { min: 10, message: transGeneral("content_must_num", { num: 10 }) },
            ]}>
            <TextArea
              rows={4}
              placeholder={transGeneral("pl_leave_your_comment_here")}
              size="large"
              onBlur={(e) => {
                formRef.setFieldsValue({
                  comment: e.target.value.trim(),
                })
              }}
            />
          </Form.Item>

          <div className="pt-4 flex items-center gap-2 w-full md:w-1/2 mx-auto">
            <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>
    </>
  )
})
