"use client"

import { Button, Form, Input, Select, Upload } from "antd"
import classNames from "classnames"
import dynamic from "next/dynamic"
import { useEffect, useState } from "react"
import { CustomCkEditerCss } from "../Books/style"
import { useTranslations } from "next-intl"
import Image from "next/image"
import { CloudUploadOutlined } from "@ant-design/icons"
import { formatDuration, formatFileSize, getAudioDuration } from "@/util/Common"
import { round } from "lodash"
import CustomEditor from "../Common/CustomEditor"
import { useNotificationContext } from "../Layout/NotificationContext"
import { useUploadAudio, useUploadImage } from "@/hook/useMedia"
import { LoadingBox } from "../Common/LoadingBox"
import { useAddSongToAlbum, useUpdateSong } from "@/hook/useMusic"
// const CustomEditor = dynamic(() => import("@/component/Common/CustomEditor"), { ssr: false })

type IProps = {
  submit: boolean
  cancel: boolean
  album: any
  song?: any
  onError: () => void
  onCancel: () => void
  onChangeValue: (values: any) => void
  onSuccess: () => void
}

export default function FormSong({ submit, cancel, album, song, onError, onChangeValue, onCancel, onSuccess }: IProps) {
  const [formRef] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const tranButton = useTranslations("button")
  const [audioDuration, setAudioDuration] = useState<number>(0)
  const tranForm = useTranslations("form")
  const trans = useTranslations("music")
  const transMessage = useTranslations("message")
  const transRq = useTranslations("required")
  const { notify } = useNotificationContext()
  const uploadImage = useUploadImage()
  const uploadAudio = useUploadAudio()
  const addSongToAlbum = useAddSongToAlbum()
  const updateSong = useUpdateSong()

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

  useEffect(() => {
    if (song) {
      formRef.setFieldsValue({
        title: song.title,
        artist: song.artist,
        description: song.description,
        poster: song.poster ? [{ uid: song.poster, response: { url: song.poster } }] : null,
        file: song.file ? [{ uid: song.file, response: { url: song.file } }] : null,
      })
      setAudioDuration(Number(song?.duration) || 0)
    } else {
      formRef.resetFields()
    }
  }, [song])

  const handleCancel = () => {
    formRef.resetFields()
    onCancel()
  }

  const onFinish = (values: any) => {
    setLoading(true)
    const params = Object.assign({}, values)
    const poster = formRef.getFieldValue("poster")
    const file = formRef.getFieldValue("file")
    if (poster && poster[0].response?.name) {
      params.poster = poster[0].response?.name
    } else delete params.poster
    if (file && file[0].response?.name) {
      params.file = file[0].response?.name
    } else delete params.file
    if (song) {
      updateSong
        .mutateAsync({ id: song?.id, body: params })
        .then(() => {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Update Song 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,
          })
          onError()
        })
        .finally(() => {
          setLoading(false)
        })
    } else {
      addSongToAlbum
        .mutateAsync({ id: album?.id, body: params })
        .then(() => {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Create Song 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,
          })
          onError()
        })
        .finally(() => {
          setLoading(false)
        })
    }
  }

  useEffect(() => {
    if (cancel) {
      formRef.resetFields()
    } else if (submit) {
      formRef.submit()
    }
  }, [submit, cancel])

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

  const handleChangeForm = (_: any, allValues: any) => {
    onChangeValue(allValues)
  }

  const handleUploadImage = 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 handleUploadAudio = async (options: any) => {
    const { file, onSuccess, onError } = options
    try {
      const response = await uploadAudio.mutateAsync({ audio: 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?.audio
          : error?.response?.data?.msgs || transMessage("error_during_upload")
      notify({
        type: "error",
        message: transMessage("fail"),
        description: message,
      })
      setAudioDuration(0)
      onError(error)
    }
  }

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

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

  return (
    <Form
      name="add_song"
      form={formRef}
      onFinish={onFinish}
      onError={() => onError()}
      autoComplete="off"
      layout="vertical"
      onValuesChange={handleChangeForm}
      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">
          <Form.Item
            label={tranForm("title")}
            name="title"
            rules={[
              { required: true, message: tranForm("placeholder_input", { name: tranForm("title") }) },
              { max: 1024, message: "Title max 1024" },
            ]}>
            <Input
              placeholder={tranForm("placeholder_input", { name: tranForm("title") })}
              size="large"
              onBlur={(e) => {
                formRef.setFieldsValue({
                  title: e.target.value.trim(),
                })
              }}
            />
          </Form.Item>
          <Form.Item
            label={trans("artist")}
            name="artist"
            rules={[{ required: true, message: transRq("cannot_empty") }]}>
            <Input
              placeholder={tranForm("placeholder_input", { name: trans("artist") })}
              size="large"
              onBlur={(e) => {
                formRef.setFieldsValue({
                  artist: 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="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.poster !== currentValues.poster}>
              {({ getFieldValue }) => {
                const fileList = getFieldValue("poster")
                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 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}
                            className="max-w-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={triggerUploadImage}
                          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({ poster: 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="poster"
                      valuePropName="fileList"
                      getValueFromEvent={normFile}
                      className={fileList ? "hidden" : ""}
                      rules={[{ required: true, message: transRq("cannot_empty") }]}>
                      <Upload
                        accept="image/*"
                        showUploadList={false}
                        listType="picture-card"
                        maxCount={1}
                        name="thumbnail"
                        customRequest={handleUploadImage}
                        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 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")}
              </span>
            </p>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.file !== currentValues.file}>
              {({ getFieldValue }) => {
                const fileListAudio = getFieldValue("file")
                if (fileListAudio) {
                  const file = fileListAudio[0]?.originFileObj
                  if (!audioDuration && file) {
                    getAudioDuration(file)
                      .then((duration: any) => {
                        if (duration) {
                          setAudioDuration(round(duration))
                        }
                      })
                      .catch((error) => {
                        console.error(error)
                      })
                  }
                }
                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)] h-52 ${
                        fileListAudio ? "flex" : "hidden"
                      }`}>
                      <div className="grow h-full max-w-[75%] xl:max-w-[80%] bg-[var(--secondary-70)] rounded-lg flex flex-col justify-center items-center text-white">
                        {fileListAudio && fileListAudio[0] && fileListAudio[0]?.response?.url ? (
                          <>
                            <Image
                              alt=""
                              src="/img/icon/music_note.svg"
                              width={62}
                              height={62}
                              className="max-w-full max-h-full object-cover"
                            />
                            <span className="font-medium text-xs mb-1">{song && !fileListAudio[0]?.name ? song?.fileorgname : fileListAudio[0]?.name}</span>
                            <span className="text-[10px]">
                              {song && !fileListAudio[0]?.size ? formatFileSize(Number(song?.filesize) || 0) : formatFileSize(fileListAudio[0]?.size || 0)} |{" "}
                              {formatDuration(audioDuration)}
                            </span>
                          </>
                        ) : fileListAudio && fileListAudio[0] && fileListAudio[0]?.error ? (
                          <>
                            <Image
                              alt=""
                              src="/img/icon/music_note.svg"
                              width={62}
                              height={62}
                              className="max-w-full max-h-full object-cover"
                            />
                            <span className="font-medium text-xs mb-1">Error</span>
                          </>
                        ) : (
                          <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={triggerUploadAudio}
                          className="group bg-[var(--secondary-100)] inline-flex justify-center items-center rounded hover:opacity-80 w-8 h-8 mb-2">
                          <Image
                            src="/img/icon/refresh_white.svg"
                            alt="share"
                            width={24}
                            height={24}
                          />
                        </button>
                        <button
                          type="button"
                          onClick={() => {
                            formRef.setFieldsValue({ file: null })
                            setAudioDuration(0)
                          }}
                          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="file"
                      valuePropName="fileList"
                      className={fileListAudio ? "hidden" : ""}
                      getValueFromEvent={normFile}
                      rules={[{ required: true, message: transRq("cannot_empty") }]}>
                      <Upload
                        accept="audio/mp3"
                        showUploadList={false}
                        listType="picture-card"
                        maxCount={1}
                        name="audio"
                        customRequest={handleUploadAudio}
                        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>
          </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>
  )
}
