"use client"

import { Button, Drawer, Form, Input, Upload } from "antd"
import classNames from "classnames"
import { DrawerCss } from "../Calendar/style"
import dynamic from "next/dynamic"
import { useEffect, useState } from "react"
import { CloudUploadOutlined } from "@ant-design/icons"
import Image from "next/image"
import { CustomAlbumEditorCss, CustomAlbumUploadCss } from "./style"
import { formatFileSize } from "@/util/Common"
import dayjs from "dayjs"
import { useTranslations } from "next-intl"
import CustomEditor from "../Common/CustomEditor"
import { useCreatePhotoAlbum, useUpdatePhotoAlbum } from "@/hook/usePhoto"
import { useNotificationContext } from "../Layout/NotificationContext"
import { LoadingBox } from "../Common/LoadingBox"
import { useUploadImage } from "@/hook/useMedia"
import { useCreateVideoAlbum, useUpdateVideoAlbum } from "@/hook/useVideo"
// const CustomEditor = dynamic(() => import("@/component/Common/CustomEditor"), { ssr: false })

type IProps = {
  isOpen: boolean
  album?: any
  type: "photo" | "video"
  setOpen: (value: boolean) => void
  onSuccess: () => void
}

export default function FormAlbum({ isOpen, album, setOpen, onSuccess, type }: IProps) {
  const [formRef] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const tranButton = useTranslations("button")
  const tranForm = useTranslations("form")
  const trans = useTranslations("media")
  const transMessage = useTranslations("message")
  const createNewPhotoAlbum = useCreatePhotoAlbum()
  const { notify } = useNotificationContext()
  const uploadImage = useUploadImage()
  const updatePhotoAlbum = useUpdatePhotoAlbum()
  const createVideoAlbum = useCreateVideoAlbum()
  const updateVideoAlbum = useUpdateVideoAlbum()

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

  useEffect(() => {
    setLoading(false)
    if (album) {
      formRef.setFieldsValue({
        fileList: [
          {
            uid: "-1",
            name: "--",
            status: "done",
            url: album.cover,
            size: undefined,
            response: {
              url: album.cover,
            },
          },
        ],
        title: album.title,
        description: album.description,
      })
    } else {
      formRef.resetFields()
    }
  }, [album])

  const onFinish = (values: any) => {
    setLoading(true)
    const params = Object.assign({}, values)
    const fileList = formRef.getFieldValue("fileList")
    if (fileList && fileList[0].response?.name) {
      params.cover = fileList[0].response?.name
      delete params.fileList
    } else delete params.fileList
    if (album) {
      params.id = album?.id
      if (type === "photo") {
        updatePhotoAlbum
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Update album successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: message,
            })
          })
          .finally(() => {
            setLoading(false)
          })
      } else {
        updateVideoAlbum
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Update album successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: message,
            })
          })
          .finally(() => {
            setLoading(false)
          })
      }
    } else {
      if (type === "photo") {
        createNewPhotoAlbum
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Create new album successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: message,
            })
          })
          .finally(() => {
            setLoading(false)
          })
      } else {
        createVideoAlbum
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Create new album successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: message,
            })
          })
          .finally(() => {
            setLoading(false)
          })
      }
    }
  }

  const handleCancel = () => {
    formRef.resetFields()
    setOpen(false)
  }

  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) {
        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)
    }
  }

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

  return (
    <Drawer
      className={classNames(``, DrawerCss)}
      closable
      destroyOnClose
      title={<p>{album ? "Edit Album" : "Create New Album"}</p>}
      placement="right"
      open={isOpen}
      onClose={() => setOpen(false)}
      width={594}>
      <Form
        name="form_album"
        form={formRef}
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
        className={classNames(CustomAlbumEditorCss, CustomAlbumUploadCss)}>
        <div className="bg-[var(--secondary-10)] rounded-lg px-4 lg:px-6 py-6">
          <p className="text-base font-semibold mb-6">{trans("album_information")}</p>
          <Form.Item
            label={tranForm("title")}
            name="title"
            rules={[
              { required: true, message: "Input the photo album title" },
              { max: 2048, message: "Photo album title max 1024" },
            ]}>
            <Input
              placeholder="Input the photo album 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>
          <p className="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.fileList !== currentValues.fileList}>
            {({ getFieldValue }) => {
              const fileList = getFieldValue("fileList")
              return (
                <>
                  <div className={`items-stretch gap-4 md:gap-6 ${fileList ? "flex" : "hidden"}`}>
                    <div className="h-32 w-40 shrink-0">
                      {fileList && fileList[0] && fileList[0]?.response?.url ? (
                        <Image
                          alt=""
                          src={fileList[0]?.response ? fileList[0]?.response?.url : URL.createObjectURL(fileList[0]?.originFileObj)}
                          width={157}
                          height={130}
                          style={{
                            width: "100%",
                            height: "100%",
                          }}
                          className="max-w-full max-h-full rounded-lg aspect-[4/1]"
                        />
                      ) : 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 grow justify-between">
                      {fileList && fileList[0] && fileList[0]?.response ? (
                        <div>
                          <p className="font-semibold">{fileList[0].name}</p>
                          <p>{formatFileSize(fileList[0]?.size || 0)}</p>
                          <p>{dayjs(fileList[0]?.lastModifiedDate).format("MMM DD, YYYY")}</p>
                        </div>
                      ) : null}
                      <div className="flex gap-2 items-center">
                        <button
                          type="button"
                          onClick={triggerUpload}
                          className="group bg-[var(--primary--70)] 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({ fileList: 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>
                  </div>
                  <Form.Item
                    label=""
                    name="fileList"
                    valuePropName="fileList"
                    className={fileList ? "hidden" : ""}
                    getValueFromEvent={normFile}
                    rules={[{ required: true, message: "Input Thumbnail" }]}>
                    <Upload
                      accept="image/*"
                      showUploadList={false}
                      maxCount={1}
                      customRequest={handleUpload}
                      listType="picture-card">
                      <span className="flex flex-col items-center text-[var(--secondary-100)] font-semibold px-4 hover:text-[var(--primary--70)]">
                        <CloudUploadOutlined className="text-4xl" />
                        <span>{tranForm("upload_file")}</span>
                      </span>
                    </Upload>
                  </Form.Item>
                </>
              )
            }}
          </Form.Item>
          <p className="py-4">(8MB Aspect ratio width and height 4:1)</p>
        </div>
        <div className="pt-4 flex items-center justify-end gap-2">
          <Button
            className="md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 !rounded-lg !border-[var(--secondary-20)] !bg-white !px-6"
            loading={loading}
            onClick={handleCancel}>
            {tranButton("cancel")}
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            className="md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 !rounded-lg !px-8 xl:!px-10 disabled:opacity-70"
            loading={loading}>
            {tranButton("submit")}
          </Button>
        </div>
      </Form>
    </Drawer>
  )
}
