"use client"

import { Button, Drawer, Form, Input, Select, Upload } from "antd"
import classNames from "classnames"
import { DrawerCss } from "../Calendar/style"
import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import { CustomCkEditerCss } from "../Books/style"
import dynamic from "next/dynamic"
import { filterOption } from "@/util/Common"
import Image from "next/image"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faPlus, faSpinner } from "@fortawesome/free-solid-svg-icons"
import { CloudUploadOutlined } from "@ant-design/icons"
import { useUploadImage } from "@/hook/useMedia"
import NotifyCustom from "../Common/NotifyCustom"
import CustomEditor from "../Common/CustomEditor"
import { LoadingBox } from "../Common/LoadingBox"
// const CustomEditor = dynamic(() => import("@/component/Common/CustomEditor"), { ssr: false })

type IProps = {
  product?: any
  isOpen: boolean
  setOpen: (value: boolean) => void
}

export default function FormProduct({ product, isOpen, setOpen }: IProps) {
  const [formRef] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const tranButton = useTranslations("button")
  const tranForm = useTranslations("form")
  const tranContact = useTranslations("contact")
  const trans = useTranslations("market")
  const tranKuisine = useTranslations("kuisine")
  const transMessage = useTranslations("message")
  const [openNotify, setOpenNotify] = useState(false)
  const [messageNotify, setMessageNotify] = useState<{
    type: "success" | "error"
    message: string
    description: string
  }>({
    type: "error",
    message: "",
    description: "",
  })
  const uploadImage = useUploadImage()

  useEffect(() => {
    formRef.resetFields()
    setLoading(false)
  }, [])

  const onFinish = (values: any) => {
    console.log(values)
    setLoading(true)
  }

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

  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError } = options
    try {
      const response = await uploadImage.mutateAsync({ image: file })
      if (response.data.success) {
        setMessageNotify({
          type: "success",
          message: transMessage("congratulation"),
          description: transMessage("uploaded_successfully"),
        })
        setOpenNotify(true)
        onSuccess(response.data.data)
      }
    } catch (error: any) {
      const message =
        error?.response?.data?.msgs && typeof error?.response?.data?.msgs === "object"
          ? error?.response?.data?.msgs?.image
          : error?.response?.data?.msgs || transMessage("error_during_upload")
      setMessageNotify({
        type: "error",
        message: transMessage("fail"),
        description: message,
      })
      setOpenNotify(true)
      onError(error)
    }
  }

  return (
    <Drawer
      className={classNames(``, DrawerCss)}
      closable
      destroyOnClose
      title={<p>{product ? trans("edit_item_market") : trans("add_item_market")}</p>}
      placement="right"
      open={isOpen}
      onClose={() => setOpen(false)}
      width={1020}>
      <Form
        name="form_product"
        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={tranForm("title")}
                name="title"
                rules={[
                  { required: true, message: transMessage("placehoder_input_the_name", { name: tranForm("title") }) },
                  { max: 1024, message: "Product title max 1024" },
                ]}>
                <Input
                  placeholder={transMessage("placehoder_input_the_name", { name: tranForm("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="website_url"
                rules={[
                  {
                    pattern: /^(https?:\/\/)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(\/.*)?$/,
                    message: transMessage("invalid_url"),
                  },
                ]}>
                <Input
                  placeholder="https://www.yourwebsite.com"
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      publisher_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 mb-4">
              <p className="text-base font-semibold mb-6">{tranContact("contact")}</p>
              <Form.Item
                label={tranContact("email")}
                name="email"
                rules={[
                  { required: true, message: "Input email, please" },
                  { type: "email", message: "Invalid email" },
                  { max: 254, message: "Email max 254" },
                ]}>
                <Input
                  placeholder="Input 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_required_but_used_establishing")})</span>
                  </p>
                }
                name="address"
                rules={[{ max: 4096, message: "Address max 4096" }]}>
                <Input
                  placeholder="Input your Contact 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_required_but_used_establishing")})</span>
                  </p>
                }
                name="city"
                rules={[{ max: 4096, message: "City max 4096" }]}>
                <Input
                  placeholder={transMessage("placehoder_input_the_name", { name: 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_required_but_used_establishing")})</span>
                  </p>
                }
                name="state"
                rules={[{ max: 4096, message: "State max 4096" }]}>
                <Input
                  placeholder="Input your Contact state"
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      state: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={tranForm("country")}
                name="country"
                rules={[{ required: true, message: "Choose type" }]}>
                <Select
                  showSearch
                  size="large"
                  placeholder="Select the Contact Country"
                  filterOption={filterOption}
                  options={[
                    { value: "1", label: "Jack" },
                    { value: "2", label: "Lucy" },
                    { value: "3", label: "Tom" },
                  ]}
                />
              </Form.Item>
              <Form.Item
                label={tranForm("postal_code")}
                name="postal_code"
                rules={[
                  { required: true, message: tranForm("postal_code") },
                  { max: 1024, message: "Product title max 1024" },
                ]}>
                <Input
                  placeholder={transMessage("placehoder_input_the_name", { name: tranForm("postal_code") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      postal_code: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={tranKuisine("contact_name")}
                name="contact_name"
                rules={[
                  { required: true, message: transMessage("placehoder_input_the_name", { name: tranKuisine("contact_name") }) },
                  { max: 1024, message: "Contact name max 1024" },
                ]}>
                <Input
                  placeholder={transMessage("placehoder_input_the_name", { name: tranKuisine("contact_name") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      contact_name: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <p className="mb-6">
                <span className="text-[var(--danger-50)]">*</span> {tranKuisine("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="prefix"
                  rules={[{ required: true, message: "Input phone number, please" }]}>
                  <Select
                    size="large"
                    filterOption={filterOption}
                    options={[
                      { value: "1", label: "+1" },
                      { value: "6", label: "+6" },
                      { value: "84", label: "+84" },
                    ]}
                  />
                </Form.Item>
                <Form.Item
                  className="col-span-8 lg:col-span-9 xl:col-span-10"
                  label=""
                  name="phone"
                  rules={[
                    { required: true, message: "Input phone number, please" },
                    { pattern: /^[0-9]{10}$/, message: "Invalid phone number" },
                  ]}>
                  <Input
                    placeholder={transMessage("placehoder_input_the_name", { name: tranKuisine("contact_number") })}
                    size="large"
                    onBlur={(e) => {
                      formRef.setFieldsValue({
                        phone: 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="type"
                rules={[{ required: true, message: "Choose type" }]}>
                <Select
                  showSearch
                  size="large"
                  placeholder="Select type"
                  filterOption={filterOption}
                  options={[
                    { value: "1", label: "Jack" },
                    { value: "2", label: "Lucy" },
                    { value: "3", label: "Tom" },
                  ]}
                />
              </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"
                rules={[{ required: true, message: "Choose type" }]}>
                <Select
                  showSearch
                  size="large"
                  placeholder="Select Category"
                  filterOption={filterOption}
                  options={[
                    { value: "1", label: "Jack" },
                    { value: "2", label: "Lucy" },
                    { value: "3", label: "Tom" },
                  ]}
                />
              </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 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.fileList !== currentValues.fileList}>
                {({ getFieldValue }) => {
                  const fileList = getFieldValue("fileList")
                  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.fileList !== currentValues.fileList}>
                {({ getFieldValue }) => {
                  const fileList = getFieldValue("fileList")
                  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 px-2 xl:px-4 py-4 border-[2px]" : ""
                      }`}>
                      {fileList &&
                        fileList.map((item: any, index: number) => (
                          <div
                            key={index}
                            className="h-full relative group">
                            {item?.response?.url || item?.error ? (
                              <>
                                {item?.error ? (
                                  <Image
                                    alt=""
                                    src="/img/default_image.jpg"
                                    width={274}
                                    height={216}
                                    style={{
                                      width: "100%",
                                      height: "100%",
                                    }}
                                    className="max-w-full max-h-full object-cover"
                                  />
                                ) : (
                                  <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>
                              </>
                            ) : (
                              <LoadingBox />
                            )}
                          </div>
                        ))}
                      <Form.Item
                        label=""
                        name="fileList"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        className="!mb-0 h-20 height-custom">
                        <Upload
                          accept="image/*"
                          maxCount={6}
                          showUploadList={false}
                          customRequest={handleUpload}
                          listType="picture-card"
                          className="group">
                          {fileList ? (
                            <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>
            </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">{trans("tag")}</p>
              <Form.Item
                label=""
                name="tag"
                rules={[{ max: 4096, message: "Tag max 4096" }]}>
                <Input
                  placeholder="Add your tag"
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      tag: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
            </div>
          </div>
        </div>
        <div className="pt-8 pb-4 flex items-center justify-end gap-2">
          <Button
            className="!px-10 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={loading}>
            {tranButton("cancel")}
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            className="!px-16 md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 xl:!h-16 !rounded-lg"
            loading={loading}>
            {tranButton("submit")}
          </Button>
        </div>
      </Form>
      <NotifyCustom
        type={messageNotify.type}
        message={messageNotify.message}
        description={messageNotify.description}
        isOpen={openNotify}
        onclose={() => setOpenNotify(false)}
      />
    </Drawer>
  )
}
