"use client"

import { useRouter } from "@/i18n/routing"
import { filterOption } from "@/util/Common"
import { Button, Form, Input, Select, Spin, Upload } from "antd"
import classNames from "classnames"
import { useTranslations } from "next-intl"
import { forwardRef, useEffect, useImperativeHandle } from "react"
import { CloudUploadOutlined } from "@ant-design/icons"
import { CustomCkEditerCss } from "@component/Books/style"
import Image from "next/image"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faPlus } from "@fortawesome/free-solid-svg-icons"
import { useUploadImage } from "@/hook/useMedia"
import CustomEditor from "@component/Common/CustomEditor"
import { typeMarketOptions } from "@/config/constant"
import { useCreateMarket, useUpdateMarket } from "@/hook/useMarket"
import { isEmpty } from "lodash"
import { SelectCountry } from "@/component/Common/SelectCountries"
import { useNotificationContext } from "@/component/Layout/NotificationContext"
import { SelectMarketCategory } from "@/component/Common/SelectMarketCate"

type IProps = {
  type: "create" | "update"
  market?: any
}

const FormMarket = forwardRef(({ market, type }: IProps, ref) => {
  const [formRef] = Form.useForm()
  const router = useRouter()
  const marketOptions = typeMarketOptions()
  const { notify } = useNotificationContext()

  const trans = useTranslations("market")
  const tranButton = useTranslations("button")
  const tranRequired = useTranslations("required")
  const tranForm = useTranslations("form")
  const tranContact = useTranslations("contact")
  const transMessage = useTranslations("message")
  const transKuisine = useTranslations("kuisine")
  const transAccount = useTranslations("account")

  const uploadImage = useUploadImage()
  const updateMarket = useUpdateMarket()
  const createMarket = useCreateMarket()

  const newTyoeMarket = marketOptions.map(({ className, ...rest }) => rest)
  
  useEffect(() => {
    if (!market) {
      formRef.setFieldsValue({
        pictures: [],
      })
      return
    }

    const pictureKeys = ["picture1", "picture2", "picture3", "picture4", "picture5", "picture6"]
    const pictures =
      pictureKeys
        .map((key) => market[key])
        .filter(Boolean)
        .map((url) => ({
          uid: url,
          name: url.split("fleamarket/")[1],
          status: "done",
          url,
          response: {
            name: url.split("fleamarket/")[1],
            url,
          },
        })) || []

    formRef.setFieldsValue({
      title: market?.title,
      description: market?.description,
      web_url: market?.web_url,
      email: market?.email,
      address: market?.address,
      city: market?.city,
      state: market?.state,
      countrycode: market?.countrycode,
      zipcode: market?.zipcode,
      phone_cc: market?.phone_cc,
      phonenumber: market?.phonenumber,
      trade_type: market?.trade_type,
      tags: market?.tags,
      category_id: market?.category?.id,
      pictures,
    })
  }, [market])

  const onCancel = () => {
    formRef.resetFields()
    formRef.setFieldsValue({
      pictures: [],
    })
  }

  const onFinish = () => {
    formRef.validateFields().then(() => {
      const values = formRef.getFieldsValue()
      const params = Object.assign({}, values)
      
      values.pictures.map((file: any, index: number) => {
        params[`picture${index + 1}`] = file.response?.name || ""
      })
      
      delete params.temporaryPictures
      delete params.pictures

      if (type === "update" && market) {
        if (values.pictures.length < 6) {
          for (let i = values.pictures.length + 1; i < 7; i++) {
            params[`picture${i}`] = ""
          }
        } 
        updateMarket
          .mutateAsync({ id: market?.id, body: params })
          .then(() => {
            notify({
              type: "success",
              message: transMessage("success"),
              description: transMessage("success"),
            })
            router.push("/market")
          })
          .catch((error: any) => {
            let concatenatedMsgs = ""
            if (typeof error?.response?.data.msgs === "string") {
              concatenatedMsgs = error?.response?.data.msgs ? error?.response?.data.msgs : transMessage("error_during_upload")
            } else {
              concatenatedMsgs = error?.response?.data.msgs ? Object.values(error?.response?.data.msgs).join("<br />") : transMessage("error_during_upload")
            }
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: concatenatedMsgs,
            })
          })
      } else {
        createMarket
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("success"),
              description: "Create market successfully",
            })
            router.push("/market")
          })
          .catch((error: any) => {
            const concatenatedMsgs =
              typeof error?.response?.data.msgs === "object"
                ? Object.values(error?.response?.data.msgs).join("; ")
                : error?.response?.data.msgs || transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: concatenatedMsgs,
            })
          })
      }
    })
  }

  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError } = options
    try {
      const response = await uploadImage.mutateAsync({ image: file })
      if (response.data.success) {
        notify({
          type: "success",
          message: transMessage("congratulation"),
          description: transMessage("uploaded_successfully"),
        })
        onSuccess(response.data.data)
        if (formRef.getFieldValue("pictures")?.length < 6) {
          formRef.setFieldValue("pictures", [...formRef.getFieldValue("pictures"), { ...file, response: response.data.data }])
        }
      } else {
        let concatenatedMsgs = ""
        if (typeof response?.data.msgs === "string") {
          concatenatedMsgs = response?.data.msgs ? response?.data.msgs : transMessage("fail")
        } else {
          concatenatedMsgs = response?.data.msgs ? Object.values(response?.data.msgs).join("<br />") : transMessage("fail")
        }
        notify({
          type: "error",
          message: transMessage("fail"),
          description: concatenatedMsgs,
        })
        onError(new Error(response.data.msg))
      }
    } catch (error: any) {
      let concatenatedMsgs = ""
      if (typeof error?.response?.data.msgs === "string") {
        concatenatedMsgs = error?.response?.data.msgs ? error?.response?.data.msgs : transMessage("error_during_upload")
      } else {
        concatenatedMsgs = error?.response?.data.msgs ? Object.values(error?.response?.data.msgs).join("<br />") : transMessage("error_during_upload")
      }
      notify({
        type: "error",
        message: transMessage("fail"),
        description: concatenatedMsgs,
      })
      onError(error)
    }
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e?.fileList
  }

  useImperativeHandle(ref, () => ({
    onFinish,
    onCancel,
  }))

  return (
    <div className="px-4 py-6">
      <Spin spinning={uploadImage?.isPending}>
        <Form
          name="add_kuisine"
          form={formRef}
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical"
          className={classNames(CustomCkEditerCss)}>
          <div className="grid gap-4 grid-cols-12">
            <div className="col-span-12 lg:col-span-8">
              <div className="bg-[var(--secondary-10)] rounded-lg border border-solid border-[var(--secondary-20)] px-4 lg:px-6 pt-6 mb-4">
                <p className="text-base font-semibold mb-6">{trans("product_information")}</p>
                <Form.Item
                  label={trans("title")}
                  name="title"
                  rules={[
                    { required: true, message: tranRequired("cannot_empty") },
                    { max: 2048, message: trans("title_max_2048", { title: trans("title") }) },
                  ]}>
                  <Input
                    placeholder={trans("title")}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        title: e.target.value.trim(),
                      })
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label={tranForm("description")}
                  name="description"
                  rules={[{ required: true, message: tranForm("placeholder_input", { name: tranForm("description") }) }]}>
                  <CustomEditor />
                </Form.Item>
                <Form.Item
                  label={trans("website_url")}
                  name="web_url"
                  rules={[
                    {
                      pattern: /^(https?:\/\/)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(\/.*)?$/,
                      message: transMessage("invalid_url"),
                    },
                  ]}>
                  <Input
                    placeholder={trans("website_url")}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        web_url: e.target.value.trim(),
                      })
                    }}
                  />
                </Form.Item>
              </div>
              <div className="bg-[var(--secondary-10)] rounded-lg border border-solid border-[var(--secondary-20)] px-4 lg:px-6 pt-6">
                <p className="text-base font-semibold mb-6">{tranContact("contact")}</p>
                <Form.Item
                  label={transAccount("email_ID")}
                  name="email"
                  rules={[
                    { required: true, message: transAccount("input_email_please") },
                    { type: "email", message: transAccount("input_email_type") },
                    { max: 256, message: transAccount("name_maxnimum_num_characters", { name: transAccount("email_ID"), num: 256 }) },
                  ]}>
                  <Input
                    placeholder={transAccount("enter_your_email_address")}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        email: e.target.value.trim(),
                      })
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label={
                    <p>
                      {tranForm("address")} <span className="text-[var(--secondary-50)]">{` (${trans("not_rq_but_used")})`}</span>
                    </p>
                  }
                  name="address"
                  rules={[{ max: 2048, message: trans("title_max_2048", { title: tranForm("address") }) }]}>
                  <Input
                    placeholder={transMessage("placehoder_input_the_name", { name: trans("input_your_contact_title", { title: tranForm("address") }) })}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        address: e.target.value.trim(),
                      })
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label={
                    <p>
                      {tranForm("city")} <span className="text-[var(--secondary-50)]">{` (${trans("not_rq_but_used")})`}</span>
                    </p>
                  }
                  name="city"
                  rules={[{ max: 2048, message: trans("title_max_2048", { title: tranForm("city") }) }]}>
                  <Input
                    placeholder={transMessage("placehoder_input_the_name", { name: trans("input_your_contact_title", { title: tranForm("city") }) })}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        city: e.target.value.trim(),
                      })
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label={
                    <p>
                      {tranForm("state")} <span className="text-[var(--secondary-50)]">{` (${trans("not_rq_but_used")})`}</span>
                    </p>
                  }
                  name="state"
                  rules={[{ max: 2048, message: trans("title_max_2048", { title: tranForm("state") }) }]}>
                  <Input
                    placeholder={transMessage("placehoder_input_the_name", { name: trans("input_your_contact_title", { title: tranForm("state") }) })}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        state: e.target.value.trim(),
                      })
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label={tranForm("country")}
                  name="countrycode"
                  rules={[{ required: true, message: tranRequired("cannot_empty") }]}>
                  <SelectCountry
                    className={classNames()}
                    size="large"
                    refetchOnMount={false}
                  />
                </Form.Item>
                <Form.Item
                  label={tranForm("postal_code")}
                  name="zipcode"
                  rules={[
                    { required: true, message: transMessage("placehoder_input_the_name", { name: tranForm("postal_code") }) },
                    { max: 2048, message: trans("title_max_2048", { title: tranForm("postal_code") }) },
                  ]}>
                  <Input
                    placeholder={transMessage("placehoder_input_the_name", { name: tranForm("postal_code") })}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        zipcode: e.target.value.trim(),
                      })
                    }}
                  />
                </Form.Item>
                <p className="mb-6">
                  <span className="text-[var(--danger-50)]">*</span> {transKuisine("contact_number")}
                </p>
                <div className="grid grid-cols-12 gap-2">
                  <Form.Item
                    className="col-span-4 lg:col-span-3 xl:col-span-2"
                    label=""
                    name="phone_cc"
                    rules={[
                      { required: true, message: tranRequired("cannot_empty") },
                      {
                        pattern: /^\+\d{1,4}$/,
                        message: "Invalid Country Code (e.g., +84, +1)",
                      },
                    ]}>
                    <Input
                      placeholder="+1"
                      size="large"
                      onBlur={(e) => {
                        const value = e.target.value.trim()
                        if (!value.startsWith("+")) {
                          formRef.setFieldsValue({
                            phone_cc: `+${value}`,
                          })
                        } else {
                          formRef.setFieldsValue({ phone_cc: value })
                        }
                      }}
                      className="!text-[var(--secondary-100)]"
                    />
                  </Form.Item>
                  <Form.Item
                    className="col-span-8 lg:col-span-9 xl:col-span-10"
                    label=""
                    name="phonenumber"
                    rules={[
                      { required: true, message: tranRequired("cannot_empty") },
                      { pattern: /^[0-9]{10}$/, message: "Invalid phone number" },
                    ]}>
                    <Input
                      placeholder="00 000 0000"
                      size="large"
                      onBlur={(e) => {
                        formRef.setFieldsValue({
                          phonenumber: e.target.value.trim(),
                        })
                      }}
                      className="!text-[var(--secondary-100)]"
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
            <div className="col-span-12 lg:col-span-4">
              <div className="bg-[var(--secondary-10)] rounded-lg border border-solid border-[var(--secondary-20)] px-4 lg:px-6 pt-6 mb-4">
                <p className="text-base font-semibold mb-6">
                  <span className="text-[var(--danger-50)]">*</span> {trans("product_type")}
                </p>
                <Form.Item
                  label=""
                  name="trade_type"
                  rules={[{ required: true, message: trans("select_type_pl") }]}>
                  <Select
                    showSearch
                    size="large"
                    placeholder={trans("select_type")}
                    filterOption={filterOption}
                    options={newTyoeMarket}
                  />
                </Form.Item>
              </div>
              <div className="bg-[var(--secondary-10)] rounded-lg border border-solid border-[var(--secondary-20)] px-4 lg:px-6 pt-6 mb-4">
                <p className="text-base font-semibold mb-6">
                  <span className="text-[var(--danger-50)]">*</span> {tranForm("category")}
                </p>
                <Form.Item
                  label=""
                  name="category_id"
                  rules={[{ required: true, message: transKuisine("select_category") }]}>
                  <SelectMarketCategory size="large" />
                </Form.Item>
              </div>
              <div className="bg-[var(--secondary-10)] rounded-lg border border-solid border-[var(--secondary-20)] px-4 lg:px-6 pt-6 pb-4 mb-4">
                <p className="text-base font-semibold mb-6 flex items-center justify-between">
                  <span>
                    <span className="text-[var(--danger-50)]">*</span> {tranForm("media_max", { num: "6" })}
                  </span>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.pictures !== currentValues.pictures}>
                    {({ getFieldValue }) => {
                      const fileList = getFieldValue("pictures")
                      return (
                        <span className="flex gap-1 items-center">
                          <span>{fileList ? -fileList.length : 0}</span>
                          <Image
                            src="/img/icon/image-outline.svg"
                            alt="check"
                            width={16}
                            height={16}
                          />
                        </span>
                      )
                    }}
                  </Form.Item>
                </p>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) =>
                    prevValues.pictures !== currentValues.pictures || prevValues.temporaryPictures !== currentValues.temporaryPictures
                  }>
                  {({ getFieldValue }) => {
                    const fileList = getFieldValue("pictures")
                    return (
                      <div
                        className={`grid gap-1.5 bg-white rounded-lg border-dashed border-[var(--secondary-40)] ${
                          fileList ? "grid-cols-2 md:grid-cols-3 lg:grid-cols-1 xl:grid-cols-2 px-2 xl:px-4 py-4 border-[2px]" : ""
                        }`}>
                        {!isEmpty(fileList) &&
                          fileList.map((item: any, index: number) => (
                            <div
                              key={index}
                              className="h-full relative group">
                              {item?.response?.url ? (
                                <>
                                  <Image
                                    alt=""
                                    src={item?.response ? item?.response?.url : URL.createObjectURL(item?.originFileObj)}
                                    width={274}
                                    height={216}
                                    style={{
                                      width: "100%",
                                      height: "100%",
                                    }}
                                    className="max-w-full max-h-full object-cover"
                                  />
                                  <button
                                    type="button"
                                    onClick={() => {
                                      const updatedFiles = fileList.filter((_: any, i: any) => i !== index)
                                      formRef.setFieldsValue({ pictures: updatedFiles })
                                    }}
                                    className="absolute top-0 left-0 w-full h-full z-10 hidden group-hover:inline-flex justify-center items-center bg-[rgba(0,0,0,0.3)] rounded-sm">
                                    <Image
                                      src="/img/icon/trash_outline_white.svg"
                                      alt="share"
                                      width={24}
                                      height={24}
                                    />
                                  </button>
                                </>
                              ) : (
                                <button
                                  type="button"
                                  onClick={() => {
                                    const updatedFiles = fileList.filter((_: any, i: any) => i !== index)
                                    formRef.setFieldsValue({ pictures: updatedFiles })
                                  }}
                                  className="absolute top-0 left-0 w-full h-full z-10 hidden group-hover:inline-flex justify-center items-center bg-[rgba(0,0,0,0.3)] rounded-sm">
                                  <Image
                                    src="/img/icon/trash_outline_white.svg"
                                    alt="share"
                                    width={24}
                                    height={24}
                                  />
                                </button>
                              )}
                            </div>
                          ))}
                        <Form.Item
                          hidden
                          name="pictures"></Form.Item>
                        <Form.Item
                          label=""
                          name="temporaryPictures"
                          valuePropName="fileList"
                          getValueFromEvent={normFile}
                          className="!mb-0 h-20 height-custom custom-upload">
                          <Upload
                            disabled={uploadImage?.isPending}
                            accept="image/png, image/jpg"
                            multiple
                            showUploadList={false}
                            listType="picture-card"
                            customRequest={handleUpload}
                            className="group">
                            {fileList?.length ? (
                              fileList?.length >= 6 ? null : (
                                <button
                                  type="button"
                                  className="bg-white text-2xl inline-flex justify-center items-center transition-transform duration-100 ease-in-out group-hover:scale-110">
                                  <FontAwesomeIcon icon={faPlus} />
                                </button>
                              )
                            ) : (
                              <span className="flex gap-2 text-[var(--primary--90)] bg-[var(--primary--20)] font-semibold px-4 py-2 rounded-lg transition-transform duration-100 ease-in-out group-hover:scale-110">
                                <span>{tranForm("upload_file")}</span>
                                <CloudUploadOutlined />
                              </span>
                            )}
                          </Upload>
                        </Form.Item>
                      </div>
                    )
                  }}
                </Form.Item>
                <p className="py-4">First image goes to feed cover (8MB Aspect ratio width and height 3:2)</p>
              </div>
              <div className="bg-[var(--secondary-10)] rounded-lg border border-solid border-[var(--secondary-20)] px-4 lg:px-6 pt-6 mb-4">
                <p className="text-base font-semibold mb-6">
                  <span className="text-[var(--danger-50)]">*</span> {trans("tag")}
                </p>
                <Form.Item
                  label=""
                  name="tags">
                  <Select
                    mode="tags"
                    size="large"
                    placeholder={trans("add_your_tag")}
                  />
                </Form.Item>
              </div>
            </div>
          </div>
          <div className="pt-4 flex justify-end items-center gap-2 lg:hidden">
            <Button
              type="default"
              onClick={onCancel}
              loading={createMarket?.isPending || updateMarket?.isPending}
              className="md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 xl:!h-16 !rounded-lg !px-8 !border-[var(--secondary-20)] !bg-[var(--secondary-10)]">
              {tranButton("cancel")}
            </Button>
            <Button
              type="primary"
              onClick={onFinish}
              loading={createMarket?.isPending || updateMarket?.isPending}
              className="md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 xl:!h-16 !rounded-lg !px-8">
              {tranButton("submit")}
            </Button>
          </div>
        </Form>
      </Spin>
    </div>
  )
})

export default FormMarket
