"use client"

import { Button, Drawer, Form, Input, Upload } from "antd"
import classNames from "classnames"
import { DrawerCss } from "../Calendar/style"
import { useEffect, useState } from "react"
import { CustomAlbumEditorCss, CustomPhotoUploadCss } from "./style"
import dynamic from "next/dynamic"
import { useTranslations } from "next-intl"
import { CloudUploadOutlined } from "@ant-design/icons"
import Image from "next/image"
import { formatFileSize } from "@/util/Common"
import CustomEditor from "../Common/CustomEditor"
import { useNotificationContext } from "../Layout/NotificationContext"
import { useUploadImage, useUploadVideo } from "@/hook/useMedia"
import { useCreatePhotoToAlbum, useUpdatePhoto } from "@/hook/usePhoto"
import { IAlbum } from "@/type/Media"
import { useCreateVideoToAlbum, useUpdateVideo } from "@/hook/useVideo"
import ReactPlayer from "react-player"
import { css } from "@emotion/css"
import { LoadingBox } from "../Common/LoadingBox"
// const CustomEditor = dynamic(() => import("@/component/Common/CustomEditor"), { ssr: false })

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

export default function FormPhoto({ isOpen, setOpen, photo, type = "photo", video, onSuccess, album }: 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 tranDashboard = useTranslations("dashboard")
  const { notify } = useNotificationContext()
  const uploadImage = useUploadImage()
  const createPhotoToAlbum = useCreatePhotoToAlbum()
  const updatePhoto = useUpdatePhoto()
  const createVideoToAlbum = useCreateVideoToAlbum()
  const uploadVideo = useUploadVideo()
  const updateVideo = useUpdateVideo()

  useEffect(() => {
    if (!isOpen) {
      getDefaultData()
      setLoading(false)
    }
  }, [isOpen])

  useEffect(() => {
    getDefaultData()
  }, [photo, video])

  const getDefaultData = () => {
    if (photo) {
      formRef.setFieldsValue({
        fileList: [
          {
            uid: "-1",
            name: photo.title,
            status: "done",
            url: photo.file,
            size: Number(photo.fileorg_size),
            response: {
              url: photo.file,
            },
          },
        ],
        title: photo.title,
        description: photo.description,
      })
    } else if (video) {
      formRef.setFieldsValue({
        fileList: [
          {
            uid: "-1",
            name: video.title,
            status: "done",
            url: video.file,
            size: Number(video.filesize),
            response: {
              url: video.file,
            },
          },
        ],
        title: video.title,
        description: video.description,
      })
    } else {
      formRef.resetFields()
    }
  }

  const onFinish = (values: any) => {
    setLoading(true)
    const params = Object.assign({}, values)
    const fileList = formRef.getFieldValue("fileList")
    if (fileList && fileList[0].response?.name) {
      params.file = fileList[0].response?.name
      delete params.fileList
    } else delete params.fileList
    params.album_id = album.id
    if (type === "photo") {
      if (photo) {
        params.id = photo?.id
        updatePhoto
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Update photo successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : errors?.response?.data?.msgs || transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: message,
            })
          })
          .finally(() => {
            setLoading(false)
          })
      } else {
        createPhotoToAlbum
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Create photo successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : errors?.response?.data?.msgs || transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: message,
            })
          })
          .finally(() => {
            setLoading(false)
          })
      }
    } else {
      if (video) {
        params.id = video?.id
        updateVideo
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Update video successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : errors?.response?.data?.msgs || transMessage("fail")
            notify({
              type: "error",
              message: transMessage("something_wrong"),
              description: message,
            })
          })
          .finally(() => {
            setLoading(false)
          })
      } else {
        createVideoToAlbum
          .mutateAsync(params)
          .then(() => {
            notify({
              type: "success",
              message: transMessage("congratulation"),
              description: "Create video successfully",
            })
            onSuccess()
          })
          .catch((errors) => {
            const message =
              errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
                ? Object.values(errors?.response?.data?.msgs).join("<br />")
                : errors?.response?.data?.msgs || 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
    if (type === "photo") {
      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)
      }
    } else {
      try {
        const response = await uploadVideo.mutateAsync({ video: file })
        if (response.data.success) {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "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?.video
            : error?.response?.data?.msgs || transMessage("error_during_upload")
        notify({
          type: "error",
          message: transMessage("fail"),
          description: message,
        })
        onError(error)
      }
    }
  }

  const videoCss = css`
    div {
      height: 100%;
    }
  `

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

  return (
    <Drawer
      className={classNames(``, DrawerCss)}
      closable
      destroyOnClose
      title={<p>{photo && type === "photo" ? "Edit Photo" : type === "photo" ? "Add Photo" : video ? "Edit vVideo" : "Add Video"}</p>}
      placement="right"
      open={isOpen}
      onClose={() => setOpen(false)}
      width={594}>
      <Form
        name="form_photo"
        form={formRef}
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
        className={classNames(CustomAlbumEditorCss, CustomPhotoUploadCss)}>
        <div className="pb-6">
          <p className="text-base font-semibold mb-6">{trans("photo_information")}</p>
          <p className="mb-6 flex items-center justify-between">
            <span>
              <span className="text-[var(--danger-50)]">*</span> {type === "photo" ? `${tranDashboard("photo")} (8MB)` : "Video (50MB)"}
            </span>
          </p>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.fileList !== currentValues.fileList}>
            {({ getFieldValue }) => {
              const fileList = getFieldValue("fileList")
              return (
                <>
                  <div className={`relative md:w-fit mb-4 ${fileList ? "flex" : "hidden"}`}>
                    <div className={classNames("min-h-44 md:min-h-56 w-full md:w-96 shrink-0", videoCss)}>
                      {type === "video" && fileList && fileList[0] && fileList[0]?.response ? (
                        <ReactPlayer
                          url={fileList[0]?.response ? fileList[0]?.response?.url : URL.createObjectURL(fileList[0]?.originFileObj)}
                          playing={false}
                          width="320"
                          height="160"
                          loop={false}
                        />
                      ) : type === "photo" && fileList && fileList[0] && fileList[0]?.response ? (
                        <Image
                          alt=""
                          src={fileList[0]?.response ? fileList[0]?.response?.url : URL.createObjectURL(fileList[0]?.originFileObj)}
                          width={370}
                          height={276}
                          style={{
                            width: "100%",
                            height: "100%",
                          }}
                          className="max-w-full rounded-lg 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 justify-between absolute bottom-0 left-0 w-full bg-gradient-to-t from-[rgba(0,0,0,0.8)] to-[rgba(255,255,255,0.01)] pb-4 px-4 md:px-6 rounded-lg pt-2">
                      <div className="text-white">
                        <p className="text-xs">{fileList && fileList[0] ? fileList[0].name : ""}</p>
                        <p className="font-semibold text-xs">{fileList && fileList[0] ? formatFileSize(fileList[0]?.size || 0) : ""}</p>
                      </div>
                      <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="delete"
                            width={24}
                            height={24}
                            className="group-hover:hidden"
                          />
                          <Image
                            src="/img/icon/trash_outline_white.svg"
                            alt="delete"
                            width={24}
                            height={24}
                            className="hidden group-hover:block"
                          />
                        </button>
                      </div>
                    </div>
                  </div>
                  <Form.Item
                    label=""
                    name="fileList"
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                    className={fileList ? "hidden" : ""}
                    rules={[{ required: true, message: "Input Thumbnail" }]}>
                    <Upload
                      accept={type === "video" ? "video/mp4,video/x-m4v,video/*" : "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>
          <Form.Item
            label={type === "photo" ? "Input photo title" : tranForm("title")}
            name="title"
            rules={[
              { required: true, message: type === "photo" ? "Input the photo title" : "Input the title" },
              { max: 2048, message: type === "photo" ? "Photo title max 1024" : "Title max 1024" },
            ]}>
            <Input
              placeholder={type === "photo" ? "Input the photo title" : "Input the 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>
        </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 hover:!border-[var(--primary--70)]"
            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>
  )
}
