"use client"

import Image from "next/image"
import CommentItem from "../Comment/CommentItem"
import CommentReport from "../Comment/CommentReport"
import BookShort from "./BookShort"
import Rate from "../Common/Rate"
import Link from "next/link"
import { useEffect, useMemo, useRef, useState } from "react"
import { formatCurrency } from "@/util/Common"
import { useTranslations } from "next-intl"
import { useDeleteBook, useGetCommentBook, useRePostBook } from "@/hook/useBooks"
import { useCookies } from "next-client-cookies"
import dayjs from "dayjs"
import { useRouter } from "@/i18n/routing"
import { useCopyToClipboard } from "@/hook/useCommon"
import { useOpenChat } from "@component/Contact/Common"
import { useNotificationContext } from "@component/Layout/NotificationContext"
import { useGetProfile } from "@/hook/useAuth"
import { LoadingResult } from "../Common/LoadingResult/LoadingResult"
import { isEmpty } from "lodash"
import { FromBookComment } from "./FromBookComment"

type IProps = {
  book?: any
}

export default function BookContent({ book }: IProps) {
  const cookies = useCookies()
  const user = JSON.parse(cookies.get("logged_user") || "null")
  const urlCurrent = typeof window !== "undefined" ? window.location.href : ""
  const { isCopied, handleCopy } = useCopyToClipboard()
  const openChat = useOpenChat()
  const { notify } = useNotificationContext()

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

  const { data: dataComment } = useGetCommentBook(book?.id, book?.id ? true : false)
  const deleteBook = useDeleteBook()
  const router = useRouter()
  const rePostBook = useRePostBook()
  const { data: userData, isLoading } = useGetProfile()
  const refModalComment = useRef<null | { showModal: () => void }>(null)
  const [startSize, setStartSize] = useState(24)

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

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth >= 992) {
        setStartSize(32)
      } else {
        setStartSize(24)
      }
    }
    handleResize()
    window.addEventListener("resize", handleResize)

    return () => {
      window.removeEventListener("resize", handleResize)
    }
  }, [])

  const handleDeleteBook = () => {
    deleteBook.mutateAsync(book.id).then(() => {
      router.push("/books")
    })
  }

  const handleRePostBook = () => {
    rePostBook.mutateAsync(book.id).then(() => {
      router.refresh()
    })
  }

  const handleBuy = (uid?: string) => {
    if (uid) {
      openChat(String(uid) || "")
    } else {
      notify({
        type: "error",
        message: transMessage("something_wrong"),
        description: transMessage("user_not_exist_or_stop_used"),
      })
    }
  }

  return (
    <LoadingResult
      isLoading={isLoading}
      isShowResult={!isEmpty(book)}
      result={
        <div className="grow overflow-y-auto md:px-4 py-6">
          <div className="lg:flex items-center justify-between xl:hidden">
            <div>
              <h2 className="text-base font-bold mb-2">{book?.title}</h2>
              <ul className="flex items-center flex-wrap">
                <li
                  className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-100)] font-semibold`}>
                  {book?.category?.name}
                </li>
                <li
                  className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-60)]`}>
                  {book?.title} #{book?.pages}
                </li>
                <li
                  className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-60)]`}>
                  Volume {book?.volume}
                </li>
                <li
                  className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-60)]`}>
                  Edition {book?.edition}
                </li>
              </ul>
            </div>
            <div className="mt-6 flex gap-2 items-center xl:hidden lg:mt-0">
              {user?.id === book?.userid && (
                <button
                  type="button"
                  onClick={handleDeleteBook}
                  className="group text-[var(--secondary-100)] bg-[var(--secondary-10)] border inline-flex justify-center items-center border-[var(--secondary-20)] rounded hover:bg-[var(--primary--70)] w-12 h-12">
                  <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>
              )}
              {user?.id === book?.userid && isExpired && (
                <button
                  type="button"
                  onClick={handleRePostBook}
                  className="group text-[var(--secondary-100)] bg-[var(--secondary-10)] border inline-flex justify-center items-center border-[var(--secondary-20)] rounded hover:bg-[var(--primary--70)] w-12 h-12">
                  <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"
                  />
                </button>
              )}
              <button
                type="button"
                onClick={() => 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-12 h-12">
                <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"
                />
              </button>
              <button
                onClick={() => handleCopy(urlCurrent)}
                disabled={isCopied}
                type="button"
                className={`group text-[var(--secondary-100)] bg-[var(--secondary-10)] border inline-flex justify-center items-center border-[var(--secondary-20)] rounded hover:bg-[var(--primary--70)] w-12 h-12 ${
                  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"
                />
              </button>
              {userData?.data?.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)] min-w-20 h-12 hover:opacity-80 text-white px-5">
                  ${book?.price ? formatCurrency(book?.price) : "--"} - {transGeneral("contact_seller")}
                </button>
              )}
            </div>
          </div>
          <div className="md:flex items-start gap-6 pt-10 md:pt-6 xl:pt-0">
            <BookShort
              className="md:w-48 xl:w-[275px] md:shrink-0"
              book={book}
              handleBuy={handleBuy}
              userData={userData?.data}
              refModalComment={refModalComment}
            />
            <div className="pt-8 md:pt-0">
              <div className="hidden xl:block">
                <h2 className="text-4xl font-bold mb-2">{book?.title}</h2>
                <ul className="flex items-center">
                  <li
                    className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-100)] font-semibold`}>
                    {book?.category?.name}
                  </li>
                  <li
                    className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-60)]`}>
                    {book?.title} #{book?.pages}
                  </li>
                  <li
                    className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-60)]`}>
                    Volume {book?.volume}
                  </li>
                  <li
                    className={`text-xs pl-6 relative first:pl-0 first:before:hidden before:content-[''] before:w-2 before:h-2 before:bg-[var(--secondary-40)] before:rounded-full before:absolute before:top-1 before:left-2 text-[var(--secondary-60)]`}>
                    Edition {book?.edition}
                  </li>
                </ul>
                <p className="font-medium text-2xl mt-4 mb-6">{book?.author}</p>
                <div className="flex items-center gap-3 mb-7">
                  <Rate
                    value={book?.avg_rating || 0}
                    color="#db9a1d"
                    size={32}
                  />
                  {book?.avg_rating ? (
                    <span className="font-medium text-lg text-[var(--secondary-50)]">
                      {book?.avg_rating} {transGeneral("stars")}
                    </span>
                  ) : (
                    <span className="font-medium text-lg text-[var(--secondary-50)]">{transGeneral("no_rating_yet")}</span>
                  )}
                </div>
              </div>
              <div
                className="text-xs md:text-sm lg:text-base"
                dangerouslySetInnerHTML={{ __html: book?.short_desc }}></div>
              <hr className="my-6" />
              <div className="grid gap-4 grid-cols-2 text-left text-[0.625rem] leading-4 lg:text-xs xl:text-lg">
                <table className="w-full">
                  <tbody>
                    <tr>
                      <th className="py-1">{trans("format")}</th>
                      <td className="py-1">{book?.format}</td>
                    </tr>
                    <tr>
                      <th className="py-1">{transGeneral("language")}</th>
                      <td className="py-1">{book?.language}</td>
                    </tr>
                    <tr>
                      <th className="py-1">{trans("no_pages")}</th>
                      <td className="py-1">{book?.pages}</td>
                    </tr>
                    <tr>
                      <th className="py-1">{trans("publisher")}</th>
                      <td className="py-1">{book?.publisher}</td>
                    </tr>
                  </tbody>
                </table>
                <div>
                  <p className="font-semibold mb-2">{trans("seller")}</p>
                  <p className="text-lg font-bold mb-3">{book?.seller}</p>
                  <p className="flex items-center gap-2 md:gap-3 mb-3">
                    <span className="w-4">
                      <Image
                        src="/img/icon/mail_outline.svg"
                        alt="mail"
                        width={24}
                        height={24}
                        style={{
                          width: "100%",
                        }}
                        className=""
                      />
                    </span>
                    <Link href={`mailto:${book?.seller_email}`}>{book?.seller_email || "--"}</Link>
                  </p>
                  <p className="flex items-center gap-2 md:gap-3">
                    <span className="w-4">
                      <Image
                        src="/img/icon/call_outline.svg"
                        alt="phone"
                        width={24}
                        height={24}
                        style={{
                          width: "100%",
                        }}
                        className=""
                      />
                    </span>
                    <Link href={`tel:${book?.seller_phonenumber}`}>{book?.seller_phonenumber || "--"}</Link>
                  </p>
                </div>
              </div>
              <hr className="my-6" />
              <CommentReport
                averageRate={book?.avg_rating || 0}
                total={dataComment?.data?.summary?.total || 0}
                data={dataComment?.data?.summary?.ratings}
              />
              {dataComment?.data.comments.map((item, index) => (
                <CommentItem
                  key={index}
                  comment={item}
                  borderContent={index < dataComment?.data.comments.length - 1 ? true : false}
                />
              ))}
            </div>
          </div>
          <FromBookComment
            startSize={startSize}
            postid={book?.id}
            ref={refModalComment}
          />
        </div>
      }
    />
  )
}
