"use clinet"

import { useRouter } from "@/i18n/routing"
import { Button, Form, Input, 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 "../Books/style"
import { CloudUploadOutlined } from "@ant-design/icons"
import { filterOption } from "@/util/Common"
import Image from "next/image"
import CustomEditor from "../Common/CustomEditor"
import { LoadingBox } from "../Common/LoadingBox"
import { useUploadImage } from "@/hook/useMedia"
import { useNotificationContext } from "../Layout/NotificationContext"
import { useCreatePostForum, useGetGameForums, useUpdatePostForum } from "@/hook/useGames"
import { useSearchParams } from "next/navigation"
// const CustomEditor = dynamic(() => import("@/component/Common/CustomEditor"), { ssr: false })

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

export default function FormPostQuestion(props: IProps) {
  const searchParams = useSearchParams()
  const { submit, cancel, onError, post } = props
  const [formRef] = Form.useForm()
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const tranButton = useTranslations("button")
  const tranForm = useTranslations("form")
  const trans = useTranslations("wgn")
  const transRq = useTranslations("required")
  const uploadImage = useUploadImage()
  const transMessage = useTranslations("message")
  const { notify } = useNotificationContext()
  const { data: gameForums } = useGetGameForums()
  const createPostForum = useCreatePostForum()
  const updatePostForum = useUpdatePostForum()

  useEffect(() => {
    if (gameForums?.data && searchParams.get("type") && !post) {
      const item = gameForums?.data?.data?.forums.find((item) => item.id === searchParams.get("type"))
      if (item) {
        formRef.setFieldsValue({
          type: searchParams.get("type"),
        })
      }
    }
  }, [searchParams, gameForums, post])

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

  useEffect(() => {
    if (post) {
      formRef.setFieldsValue({
        title: post?.title,
        type: post?.forum_id,
        content: post?.content,
        thumbnail: post?.thumbnail
          ? [
              {
                uid: "-1",
                name: post.thumbnail,
                status: "done",
                url: post.thumbnail,
                response: {
                  url: post.thumbnail,
                },
              },
            ]
          : undefined,
      })
    }
  }, [post])

  const onFinish = (values: any) => {
    setLoading(true)
    const params = Object.assign({}, values)
    const thumbnail = formRef.getFieldValue("thumbnail")
    if (thumbnail && thumbnail[0].response?.name) params.thumbnail = thumbnail[0].response?.name
    else delete params.thumbnail
    if (post) {
      params.id = post.id
      updatePostForum
        .mutateAsync(params)
        .then(() => {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Update question successfully",
          })
          router.push("/wgn")
        })
        .catch((errors) => {
          onError()
          notify({
            type: "error",
            message: transMessage("something_wrong"),
            description: errors?.response?.data.msgs || transMessage("fail"),
          })
        })
    } else {
      createPostForum
        .mutateAsync(params)
        .then(() => {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Post question successfully",
          })
          router.push("/wgn")
        })
        .catch((errors) => {
          onError()
          notify({
            type: "error",
            message: transMessage("something_wrong"),
            description: errors?.response?.data.msgs || transMessage("fail"),
          })
        })
    }
  }

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

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

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

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

  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)
      }
    } 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")
      notify({
        type: "error",
        message: transMessage("fail"),
        description: message,
      })
      onError(error)
    }
  }

  return (
    <div className="px-4 py-6 grow overflow-y-auto">
      <Form
        name="add_book"
        form={formRef}
        onFinish={onFinish}
        onError={() => onError()}
        autoComplete="off"
        layout="vertical"
        className={classNames(CustomCkEditerCss)}>
        <div className="grid gap-4 grid-cols-12">
          <div className="col-span-12 lg:col-span-8 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("question_information")}</p>
            <Form.Item
              label={tranForm("title")}
              name="title"
              rules={[
                { required: true, message: "Input the topic name" },
                { max: 1024, message: "Input the topic name max 1024" },
              ]}>
              <Input
                placeholder="Input the topic name"
                size="large"
                onBlur={(e) => {
                  formRef.setFieldsValue({
                    title: e.target.value.trim(),
                  })
                }}
              />
            </Form.Item>
            <Form.Item
              label={trans("forum_type")}
              name="type"
              rules={[{ required: true, message: "Choose the topic" }]}>
              <Select
                showSearch
                size="large"
                placeholder="Select Book Category"
                disabled={post ? true : false}
                filterOption={filterOption}
                options={gameForums?.data ? gameForums?.data?.data?.forums.map((item) => ({ label: item.name, value: item.id, disable: !item.is_active })) : []}
              />
            </Form.Item>
            <Form.Item
              label={tranForm("description")}
              name="content"
              rules={[{ required: true, message: tranForm("placeholder_input", { name: tranForm("description") }) }]}>
              <CustomEditor />
            </Form.Item>
          </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 flex items-center justify-between">
                <span>
                  <span className="text-[var(--danger-50)]">*</span> {tranForm("thumbnail")}
                </span>
              </p>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) => prevValues.thumbnail !== currentValues.thumbnail}>
                {({ getFieldValue }) => {
                  const fileList = getFieldValue("thumbnail")
                  return (
                    <>
                      <div
                        className={`items-center gap-2 md:gap-6 lg:gap-2 xl:gap-4 bg-white px-2 xl:px-4 py-4 rounded-lg border-[2px] border-dashed border-[var(--secondary-40)] min-h-52 ${
                          fileList ? "flex" : "hidden"
                        }`}>
                        <div className="grow h-full max-w-[75%] xl:max-w-[80%]">
                          {fileList && fileList[0] && fileList[0]?.response?.url ? (
                            <Image
                              alt=""
                              src={fileList[0]?.response ? fileList[0]?.response?.url : URL.createObjectURL(fileList[0]?.originFileObj)}
                              width={274}
                              height={216}
                              style={{
                                width: "100%",
                                height: "100%",
                              }}
                              className="max-w-full max-h-full aspect-square object-cover"
                            />
                          ) : fileList && fileList[0] && fileList[0]?.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"
                            />
                          ) : (
                            <LoadingBox />
                          )}
                        </div>
                        <div className="flex flex-col shrink-0 basis-[2rem] w-8 md:flex-row lg:flex-col md:basis-1/3 md:gap-4 lg:gap-0 lg:basis-[2rem]">
                          <button
                            type="button"
                            onClick={triggerUpload}
                            className="group bg-[var(--secondary-100)] inline-flex justify-center items-center rounded hover:opacity-80 w-8 h-8">
                            <Image
                              src="/img/icon/refresh_white.svg"
                              alt="share"
                              width={24}
                              height={24}
                            />
                          </button>
                          <button
                            type="button"
                            onClick={() => formRef.setFieldsValue({ thumbnail: null })}
                            className="group bg-[var(--secondary-20)] inline-flex justify-center items-center rounded hover:bg-[var(--primary--70)] w-8 h-8">
                            <Image
                              src="/img/icon/trash_outline.svg"
                              alt="share"
                              width={24}
                              height={24}
                              className="group-hover:hidden"
                            />
                            <Image
                              src="/img/icon/trash_outline_white.svg"
                              alt="share"
                              width={24}
                              height={24}
                              className="hidden group-hover:block"
                            />
                          </button>
                        </div>
                      </div>
                      <Form.Item
                        label=""
                        name="thumbnail"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        className={fileList ? "hidden" : ""}
                        rules={[{ required: true, message: transRq("cannot_empty") }]}>
                        <Upload
                          accept="image/*"
                          showUploadList={false}
                          listType="picture-card"
                          maxCount={1}
                          customRequest={handleUpload}
                          className="group">
                          <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>
                    </>
                  )
                }}
              </Form.Item>
              <p className="py-4">(8MB Aspect ratio width and height 1:1)</p>
            </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>
    </div>
  )
}
