"use client"

import { Button, Form, Input, Modal } from "antd"
import { useTranslations } from "next-intl"
import { forwardRef, useEffect, useImperativeHandle, useState } from "react"
import { useNotificationContext } from "@component/Layout/NotificationContext"
import { useAddAffiliate, useUpdateCodeAffiliate } from "@/hook/useUsers"
import { useQueryClient } from "@tanstack/react-query"

type IProps = {
  code?: string
}

export const AddAffiliate = forwardRef<any, IProps>((props, ref) => {
  const { code } = props
  const [formRef] = Form.useForm()
  const { notify } = useNotificationContext()
  const queryClient = useQueryClient()

  const trans = useTranslations("profile")
  const tranButton = useTranslations("button")
  const transMessage = useTranslations("message")
  const tranRequired = useTranslations("required")
  const transAccount = useTranslations("account")

  const [isModalOpen, setIsModalOpen] = useState(false)

  const createAffiliate = useAddAffiliate()
  const updateCodeAffiliate = useUpdateCodeAffiliate()

  useEffect(() => {
    if (code) {
      formRef.setFieldsValue({
        code: code.trim(),
      })
    } else {
      formRef.resetFields()
    }
  }, [code])

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

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

    handleCancel,
  }))

  const onFinish = (values: any) => {
    const newCode = String(values?.code)
    if (code) {
      // If code already exists, update it
      updateCodeAffiliate
        .mutateAsync({ code, new_code: newCode })
        .then(() => {
          handleCancel()
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Update affiliate code successfully",
          })
        })
        .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,
          })
        })
    } else {
      createAffiliate
        .mutateAsync(newCode)
        .then(() => {
          handleCancel()
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: trans("create_affiliate_code_success"),
          })

          queryClient.invalidateQueries({ queryKey: ["users.get_list_affiliate"] })
        })
        .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
      maskClosable={false}
      open={isModalOpen}
      onCancel={handleCancel}
      title={trans("add_affiliate_code")}
      footer={null}>
      <Form
        name="add_kuisine"
        form={formRef}
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical">
        <Form.Item
          label={trans("code")}
          name="code"
          rules={[
            { required: true, message: tranRequired("cannot_empty") },
            { min: 5, message: transAccount("name_minimum_num_characters", { name: trans("code"), num: 5 }) },
            { max: 254, message: transAccount("name_maxnimum_num_characters", { name: trans("code"), num: 254 }) },
          ]}>
          <Input
            placeholder={trans("code")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                code: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
          />
        </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={createAffiliate?.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={createAffiliate?.isPending}>
            {tranButton("submit")}
          </Button>
        </div>
      </Form>
    </Modal>
  )
})
