"use clinet"

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

type IProps = {
  book?: any
  submit: boolean
  cancel: boolean
  onError: () => void
}

export default function FormBook({ submit, cancel, onError, book }: IProps) {
  const [formRef] = Form.useForm()
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const tranButton = useTranslations("button")
  const trans = useTranslations("book")
  const tranForm = useTranslations("form")
  const transGeneral = useTranslations("general")
  const transMessage = useTranslations("message")
  const transRq = useTranslations("required")
  const { data: categories } = useGetBookCategories()
  const uploadImage = useUploadImage()
  const createBook = useCreateBook()
  const { data: settings } = useBookSetting()
  const updateBook = useUpdateBook()
  const [openNotify, setOpenNotify] = useState(false)
  const [messageNotify, setMessageNotify] = useState<{
    type: "success" | "error"
    message: string
    description: string
  }>({
    type: "error",
    message: "",
    description: "",
  })

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

  useEffect(() => {
    if (book?.data) {
      const pictureKeys = ["picture1", "picture2", "picture3", "picture4", "picture5", "picture6"]
      const pictures =
        pictureKeys
          .map((key) => book.data[key])
          .filter(Boolean)
          .map((url) => ({
            uid: url,
            name: url.split("original/")[1],
            status: "done",
            url,
            response: {
              name: url.split("original/")[1],
              url,
            },
          })) || []
      formRef.setFieldsValue({
        ...book.data,
        pictures: pictures,
        // thumbnail: [
        //   {
        //     uid: "-1",
        //     name: book.data.thumbnail,
        //     status: "done",
        //     url: book.data.thumbnail,
        //     response: {
        //       url: book.data.thumbnail,
        //     },
        //   },
        // ],
        category_id: book?.data?.category?.id,
      })
    }
  }, [book])

  const onFinish = (values: any) => {
    setLoading(true)
    const params = Object.assign({}, values)
    const fileList = formRef.getFieldValue("pictures")
    // const thumbnail = formRef.getFieldValue("thumbnail")
    // if (thumbnail && thumbnail[0].response?.name) params.thumbnail = thumbnail[0].response?.name
    // else delete params.thumbnail
    if (fileList) {
      fileList.map((file: any, index: number) => {
        params[`picture${index + 1}`] = file.response?.name
      })
      delete params.pictures
      if (book) {
        if (fileList.length < 6) {
          for (let i = fileList.length + 1; i < 7; i++) {
            params[`picture${i}`] = ""
          }
        }
        params.id = book.data.id
        updateBook
          .mutateAsync(params)
          .then(() => {
            setMessageNotify({
              type: "success",
              message: transMessage("congratulation"),
              description: trans("update_book_success"),
            })
            router.push("/books")
            setOpenNotify(true)
          })
          .catch((errors) => {
            onError()
            const msgs =
              errors?.response?.data.msgs && typeof errors?.response?.data.msgs === "object"
                ? Object.values(errors?.response?.data.msgs).join("; ")
                : errors?.response?.data.msgs || transMessage("fail")
            setMessageNotify({
              type: "error",
              message: transMessage("something_wrong"),
              description: msgs,
            })
            setOpenNotify(true)
          })
      } else {
        createBook
          .mutateAsync(params)
          .then(() => {
            setMessageNotify({
              type: "success",
              message: transMessage("congratulation"),
              description: trans("create_book_success"),
            })
            router.push("/books")
            setOpenNotify(true)
          })
          .catch((errors) => {
            onError()
            const msgs =
              errors?.response?.data.msgs && typeof errors?.response?.data.msgs === "object"
                ? Object.values(errors?.response?.data.msgs).join("; ")
                : errors?.response?.data.msgs || transMessage("fail")
            setMessageNotify({
              type: "error",
              message: transMessage("something_wrong"),
              description: msgs || transMessage("fail"),
            })
            setOpenNotify(true)
          })
      }
    }
  }

  useEffect(() => {
    if (cancel) {
      formRef.resetFields()
      router.push("/books")
    } else if (submit) {
      formRef.submit()
    }
  }, [submit, cancel])

  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,
      })
      formRef.setFieldsValue({ thumbnail: null })
      setOpenNotify(true)
      onError(error)
    }
  }

  const onFinishFailed = () => {
    onError()
  }

  const handleCancel = () => {
    formRef.resetFields()
    router.push("/books")
  }

  const triggerUpload = () => {
    const fileInput = document.querySelector("input[type='file']") as HTMLInputElement
    fileInput?.click()
  }

  return (
    <div className="px-4 py-6 grow overflow-y-auto">
      <Form
        name="add_book"
        form={formRef}
        onFinish={onFinish}
        onError={() => onError()}
        autoComplete="off"
        onFinishFailed={onFinishFailed}
        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("book_information")}</p>
              <Form.Item
                label={tranForm("title")}
                name="title"
                rules={[
                  { required: true, message: "Input book title" },
                  { max: 1024, message: "Book title max 1024" },
                ]}>
                <Input
                  placeholder={trans("input_book_title")}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      title: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={tranForm("subtitle")}
                name="subtitle"
                rules={[
                  { required: true, message: "Input book subtitle" },
                  { max: 2048, message: "Subtitle max 2048" },
                ]}>
                <Input
                  placeholder={tranForm("placeholder_input", { name: tranForm("subtitle") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      subtitle: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("author_name")}
                name="author"
                rules={[
                  { required: true, message: "Input author name" },
                  { max: 2048, message: "Author name max 2048" },
                ]}>
                <Input
                  placeholder={tranForm("placeholder_input", { name: trans("author_name") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      author: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("volume_series")}
                name="volume"
                rules={[
                  { required: true, message: "Input volume/series" },
                  { max: 2048, message: "Volume/Series max 2048" },
                ]}>
                <Input
                  placeholder={trans("placehoder_volume_series")}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      volume: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("no_pages")}
                name="pages"
                rules={[{ required: true, message: "Inputnumber of page of book" }]}>
                <InputNumber
                  placeholder={trans("placehoder_no_page")}
                  size="large"
                  min={1}
                  max={100}
                  step={1}
                  className="!w-full"
                />
              </Form.Item>
              <Form.Item
                label={trans("edition")}
                name="edition"
                rules={[
                  { required: true, message: "Input edition of book" },
                  { max: 1024, message: "Edition of book max 1024" },
                  // {
                  //   pattern: /^(\d+(\.\d+)*|\d)$/,
                  //   message: "Edition must be in format like 0.1",
                  // },
                ]}>
                <Input
                  placeholder={trans("placehoder_edition")}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      edition: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={tranForm("short_desc")}
                name="short_desc"
                rules={[{ required: true, message: tranForm("placeholder_input", { name: tranForm("description") }) }]}>
                <CustomEditor />
              </Form.Item>
              {/* <Form.Item
                label={tranForm("description")}
                name="long_desc"
                rules={[{ required: true, message: tranForm("placeholder_input", { name: tranForm("description") }) }]}>
                <CustomEditor />
              </Form.Item> */}
              <Form.Item
                label={trans("editorial_review")}
                name="editorial_review"
                rules={[{ required: true, message: "Input Editorial Review" }]}>
                <CustomEditor />
              </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">{trans("publisher_seller")}</p>
              <Form.Item
                label={trans("publisher")}
                name="publisher"
                rules={[
                  { required: true, message: "Input Publisher" },
                  { max: 1024, message: "Publisher max 1024" },
                ]}>
                <Input
                  placeholder={tranForm("placeholder_input", { name: trans("publisher") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      publisher: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("publisher_url")}
                name="url"
                rules={[
                  {
                    pattern: /^(https?:\/\/)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(\/.*)?$/,
                    message: transMessage("invalid_url"),
                  },
                ]}>
                <Input
                  placeholder={tranForm("placeholder_input", { name: trans("publisher_url") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      url: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("seller_name")}
                name="seller">
                <Input
                  placeholder={tranForm("placeholder_input", { name: trans("seller_name") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      seller: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("seller_email")}
                name="seller_email"
                rules={[{ type: "email", message: "input email type" }]}>
                <Input
                  placeholder={tranForm("placeholder_input", { name: trans("seller_email") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      seller_email: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label="Seller Phone Number"
                name="seller_phonenumber">
                <Input
                  placeholder="00 000 0000"
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      seller_phonenumber: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("seller_address")}
                name="seller_address">
                <Input
                  placeholder={tranForm("placeholder_input", { name: trans("seller_address") })}
                  size="large"
                  onBlur={(e) => {
                    formRef.setFieldsValue({
                      seller_address: e.target.value.trim(),
                    })
                  }}
                />
              </Form.Item>
              <Form.Item
                label={trans("seller_type")}
                name="sell_type">
                <Select
                  showSearch
                  size="large"
                  placeholder={tranForm("placeholder_select", { name: trans("seller_type") })}
                  filterOption={filterOption}
                  options={
                    settings?.data?.sell_type
                      ? settings?.data?.sell_type.map((item: any) => {
                          return {
                            value: item,
                            label: item,
                          }
                        })
                      : []
                  }
                />
              </Form.Item>
            </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> {tranForm("category")}
              </p>
              <Form.Item
                label=""
                name="category_id"
                rules={[{ required: true, message: "Select Category" }]}>
                <Select
                  showSearch
                  size="large"
                  placeholder={tranForm("placeholder_select", { name: tranForm("category") })}
                  filterOption={filterOption}
                  options={
                    categories?.data
                      ? categories?.data.map((item) => {
                          return {
                            value: item.id,
                            label: item.name,
                          }
                        })
                      : []
                  }
                />
              </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("price")}
              </p>
              <Form.Item
                label=""
                name="price"
                rules={[{ required: true, message: "Input price" }]}>
                <InputNumber
                  placeholder="$0.00"
                  size="large"
                  min={0}
                  step={0.1}
                  className="!w-full"
                />
              </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.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}>
                {({ 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 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="pictures"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        className="!mb-0 h-20 height-custom">
                        <Upload
                          accept="image/*"
                          maxCount={6}
                          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("format")}
              </p>
              <Form.Item
                label=""
                name="format"
                rules={[{ required: true, message: "Choose type" }]}>
                <Select
                  showSearch
                  size="large"
                  placeholder={tranForm("placeholder_select", { name: trans("format") })}
                  filterOption={filterOption}
                  options={
                    settings?.data?.format
                      ? settings?.data?.format.map((item: any) => {
                          return {
                            value: item,
                            label: item,
                          }
                        })
                      : []
                  }
                />
              </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">
                <span className="text-[var(--danger-50)]">*</span> {transGeneral("language")}
              </p>
              <Form.Item
                label=""
                name="language"
                rules={[{ required: true, message: "Choose type" }]}>
                <Select
                  showSearch
                  size="large"
                  placeholder={tranForm("placeholder_select", { name: transGeneral("language") })}
                  filterOption={filterOption}
                  options={
                    settings?.data?.language
                      ? settings?.data?.language.map((item: any) => {
                          return {
                            value: item,
                            label: item,
                          }
                        })
                      : []
                  }
                />
              </Form.Item>
            </div>
          </div>
        </div>
        <div className="pt-4 flex items-center gap-2 md:hidden">
          <Button
            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={loading}
            onClick={handleCancel}>
            {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={loading}>
            {tranButton("submit")}
          </Button>
        </div>
      </Form>
      <NotifyCustom
        type={messageNotify.type}
        message={messageNotify.message}
        description={messageNotify.description}
        isOpen={openNotify}
        onclose={() => setOpenNotify(false)}
      />
    </div>
  )
}
