"use client"

import { useFavouriteBook, useUnfavouriteBook } from "@/hook/useBooks"
import { useRouter } from "@/i18n/routing"
import dayjs from "dayjs"
import { useCookies } from "next-client-cookies"
import { useTranslations } from "next-intl"
import Image from "next/image"
import { useMemo } from "react"
import { useNotificationContext } from "../Layout/NotificationContext"
import { useCopyToClipboard } from "@/hook/useCommon"
import { formatCurrency } from "@/util/Common"
import { IUserProfile } from "@/type/User"
import CarouselImage from "../Common/CarouselImage"

type IProps = {
  className?: string
  book?: any
  handleBuy: (uid?: string) => void
  userData?: IUserProfile
  refModalComment?: React.RefObject<any>
}

export default function BookShort({ className, book, handleBuy, userData, refModalComment }: IProps) {
  const cookies = useCookies()
  const router = useRouter()
  const user = JSON.parse(cookies.get("logged_user") || "null")
  const { notify } = useNotificationContext()
  const { isCopied, handleCopy } = useCopyToClipboard()
  const urlCurrent = typeof window !== "undefined" ? window.location.href : ""

  const trans = useTranslations("book")
  const transGeneral = useTranslations("general")
  const tranContact = useTranslations("contact")
  const transMessage = useTranslations("message")

  const favouriteBook = useFavouriteBook()
  const unfavouriteBook = useUnfavouriteBook()

  const isExpired = useMemo(() => {
    return book?.expirydate ? dayjs().isAfter(dayjs.unix(Number(book.expirydate))) : false
  }, [book])

  const pictures = useMemo(() => {
    const filterPicture = Object.keys(book)
      .filter((key) => key.startsWith("picture") && key.endsWith("_org_name") === false)
      .map((key) => book[key])
      .filter((item) => item !== "")
    return filterPicture
  }, [book])

  const handleFavorite = () => {
    favouriteBook
      .mutateAsync(book.id)
      .then(() => {
        router.refresh()
      })
      .catch((error) => {
        const concatenatedMsgs = error?.response?.data.msgs || transMessage("fail")
        notify({
          type: "error",
          message: transMessage("something_wrong"),
          description: concatenatedMsgs,
        })
      })
  }

  const handleUnfavorite = () => {
    unfavouriteBook
      .mutateAsync(book.id)
      .then(() => {
        router.refresh()
      })
      .catch((error) => {
        const concatenatedMsgs = error?.response?.data.msgs || transMessage("fail")
        notify({
          type: "error",
          message: transMessage("something_wrong"),
          description: concatenatedMsgs,
        })
      })
  }

  return (
    <div className={`flex items-center flex-col ${className}`}>
      <div className="w-48 md:w-full xl:mb-8">
        <CarouselImage images={pictures} />
        {/* <Image
          src={book?.picture1 || "/img/default_image.jpg"}
          alt={book?.title ?? ""}
          width={275}
          height={400}
          onError={(e) => (e.currentTarget.src = "/img/default_image.jpg")}
          className="w-full aspect-[6/5] object-cover"
        /> */}
      </div>
      <div className="w-48 md:w-full">
        <div className="hidden xl:flex pb-4 flex-col gap-4">
          {userData?.id === book?.user?.id ? (
            <button
              type="button"
              className="inline-flex justify-center items-center gap-3 rounded bg-[var(--primary--70)] min-w-20 h-12 hover:opacity-80 text-white px-5"
              onClick={() => {
                router.push(`/books/update-book/${book?.id}`)
              }}>
              <Image
                src="/img/icon/edit_white.svg"
                alt="share"
                width={24}
                height={24}
              />
              {trans("edit")}
            </button>
          ) : (
            <button
              onClick={() => handleBuy(book?.user?.id)}
              type="button"
              className="inline-flex justify-center items-center rounded bg-[var(--primary--70)] w-full py-4 h-14 hover:opacity-80 text-white px-4">
              ${book?.price ? formatCurrency(book?.price) : "--"} - {transGeneral("contact_seller")}
            </button>
          )}
          <button
            type="button"
            onClick={() => refModalComment && refModalComment?.current?.showModal()}
            className="group text-[var(--secondary-100)] bg-[var(--secondary-10)] border inline-flex justify-center gap-3 items-center border-[var(--secondary-20)] rounded hover:bg-[var(--primary--70)] hover:text-white group w-full py-4">
            <Image
              src="/img/icon/chatbox.svg"
              alt="message"
              width={24}
              height={24}
              className="group-hover:hidden"
            />
            <Image
              src="/img/icon/chatbox_white.svg"
              alt="message"
              width={24}
              height={24}
              className="hidden group-hover:block"
            />
            <span>{transGeneral("leave_comment")}</span>
          </button>
          <button
            onClick={() => handleCopy(urlCurrent)}
            disabled={isCopied}
            type="button"
            className={`group text-[var(--secondary-100)] bg-[var(--secondary-10)] border inline-flex justify-center gap-3 items-center border-[var(--secondary-20)] rounded hover:bg-[var(--primary--70)] hover:text-white group w-full py-4 ${
              isCopied ? "opacity-50" : ""
            }`}>
            <Image
              src="/img/icon/redo.svg"
              alt="share"
              width={24}
              height={24}
              className="group-hover:hidden"
            />
            <Image
              src="/img/icon/redo_white.svg"
              alt="share"
              width={24}
              height={24}
              className="hidden group-hover:block"
            />
            <span>{trans("share_book_link")}</span>
          </button>
          {user?.id === book?.userid && isExpired && (
            <button
              type="button"
              className="group text-[var(--secondary-100)] bg-[var(--secondary-10)] border inline-flex justify-center gap-3 items-center border-[var(--secondary-20)] rounded hover:bg-[var(--primary--70)] hover:text-white group w-full py-4">
              <Image
                src="/img/icon/refresh.svg"
                alt="share"
                width={24}
                height={24}
                className="group-hover:hidden"
              />
              <Image
                src="/img/icon/refresh_white.svg"
                alt="share"
                width={24}
                height={24}
                className="hidden group-hover:block"
              />
              <span>{trans("repost_book")}</span>
            </button>
          )}
          {user?.id === book?.userid && (
            <button
              type="button"
              className="group text-[var(--secondary-100)] bg-[var(--secondary-10)] border inline-flex justify-center gap-3 items-center border-[var(--secondary-20)] rounded hover:bg-[var(--primary--70)] hover:text-white group w-full py-4">
              <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"
              />
              <span>{trans("delete_book")}</span>
            </button>
          )}
        </div>
        {book?.is_favourite ? (
          <button
            type="button"
            onClick={handleUnfavorite}
            className="font-medium text-[var(--secondary-100)] bg-[var(--secondary-20)] inline-flex justify-center items-center gap-3 w-full py-4 hover:bg-[var(--primary--70)] hover:text-white group xl:bg-[var(--secondary-10)] xl:rounded xl:border xl:border-[var(--secondary-20)]">
            <Image
              src="/img/icon/broken_heart.svg"
              alt="broken_heart"
              width={24}
              height={24}
              className="group-hover:hidden"
            />
            <Image
              src="/img/icon/broken_heart_white.svg"
              alt="broken_heart"
              width={24}
              height={24}
              className="hidden group-hover:block"
            />
            <span>{tranContact("remove_favorite")}</span>
          </button>
        ) : (
          <button
            type="button"
            onClick={handleFavorite}
            className="font-medium text-[var(--secondary-100)] bg-[var(--secondary-20)] inline-flex justify-center items-center gap-3 w-full py-4 hover:bg-[var(--primary--70)] hover:text-white group xl:bg-[var(--secondary-10)] xl:rounded xl:border xl:border-[var(--secondary-20)]">
            <Image
              src="/img/icon/heart_outline.svg"
              alt="broken_heart"
              width={24}
              height={24}
              className="group-hover:hidden"
            />
            <Image
              src="/img/icon/heart_outline_white.svg"
              alt="broken_heart"
              width={24}
              height={24}
              className="hidden group-hover:block"
            />
            <span>{trans("add_to_favorite")}</span>
          </button>
        )}
      </div>
    </div>
  )
}
