"use client"

import classNames from "classnames"
import Image from "next/image"
import { Link, useRouter } from "@/i18n/routing"
import { ItemNewsCss } from "./style"
import { useEffect, useState } from "react"
import dayjs from "dayjs"
import { useAddNewFavourites, useDeleteNewFavourites, useDeleteNewPost } from "@/hook/useNews"
import { useNotificationContext } from "../Layout/NotificationContext"
import { useTranslations } from "next-intl"
import { CustomDropDownMenuCss, DropDownMenu } from "@/component/Common/DropDownMenu"
import { Modal, Card, type MenuProps } from "antd"
import { ILocalArticle } from "@/type/News"
import { useSetRecoilState } from "recoil"
import { typeIsOpenEditNewsState } from "@/recoil/news"
import { renderLabelItem } from "@/component/Common/LabelItem"

type IProps = {
  className?: string
  url_image?: string
  alt_image?: string
  url?: string
  title?: string
  decs?: string
  createdAt: number
  author?: string
  keyProps: string | number
  target?: string
  is_favourite?: boolean
  showMark?: boolean
  item?: ILocalArticle
  isButtonTopRight?: boolean
  onRefect?: () => void
  onEditPost?: (post: any) => void
}

export default function CardItemNews(props: IProps) {
  const [modal, modalContextHolder] = Modal.useModal()
  const router = useRouter()
  const { notify } = useNotificationContext()

  const transBook = useTranslations("book")
  const transButton = useTranslations("button")
  const transMessage = useTranslations("message")
  const transGeneral = useTranslations("general")

  const [activeButtons, setActiveButtons] = useState<any>([])
  const setEditPost = useSetRecoilState(typeIsOpenEditNewsState)
  const [activeButton, setActiveButton] = useState<any>("")

  const deleteNewPost = useDeleteNewPost()
  const addNewFavourites = useAddNewFavourites()
  const deleteNewFavourites = useDeleteNewFavourites()

  const handleButtonClick = (index: string | number) => {
    if (activeButtons.includes(index)) {
      deleteNewFavourites
        .mutateAsync(String(index))
        .then(() => {
          notify({
            type: "success",
            message: transMessage("success"),
            description: "Success to delete favorite book",
          })
        })
        .catch((error) => {
          const concatenatedMsgs = error?.response?.data.msgs || transMessage("fail")
          notify({
            type: "error",
            message: transMessage("something_wrong"),
            description: concatenatedMsgs,
          })
        })
    } else {
      addNewFavourites
        .mutateAsync(String(index))
        .then(() => {
          notify({
            type: "success",
            message: transMessage("success"),
            description: "Success to add new favorite book",
          })
        })
        .catch((error) => {
          const concatenatedMsgs = error?.response?.data.msgs || transMessage("fail")
          notify({
            type: "error",
            message: transMessage("something_wrong"),
            description: concatenatedMsgs,
          })
        })
    }
    setActiveButtons((prev: any) => (prev.includes(index) ? prev.filter((i: string | number) => i !== index) : [...prev, index]))
  }

  useEffect(() => {
    if (props.is_favourite) {
      setActiveButtons((prev: any) => [...prev, props.keyProps])
    } else {
      setActiveButtons((prev: any) => prev.filter((i: string | number) => i !== props.keyProps))
    }
  }, [props.is_favourite])

  const handleOpenChange = (open: boolean, item: any) => {
    setActiveButton((prevId: any) => (prevId === item?.id || !open ? null : item?.id))
  }

  const handleDeleteNewPost = () => {
    deleteNewPost
      .mutateAsync(activeButton)
      .then((res: any) => {
        if (res?.status === 200) {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: transGeneral("deleted_successfully"),
          })
          props?.onRefect && props?.onRefect()
        }
      })
      .catch((errors) => {
        notify({
          type: "error",
          message: transMessage("something_wrong"),
          description: errors?.response?.data.msgs || transMessage("fail"),
        })
      })
  }

  const confirmDelete = () => {
    modal.confirm({
      title: transGeneral("confirm_delete"),
      okText: transButton("ok"),
      cancelText: transButton("cancel"),
      onOk() {
        handleDeleteNewPost()
      },
    })
  }

  const buttonTopRight = (item: any, className?: string) => {
    const items: MenuProps["items"] = [
      {
        label: renderLabelItem(transBook("go_detail"), "/img/icon/information_circle_outline.svg", "information_circle_outline"),
        key: "0",
        onClick: () => {
          router.push(`/news/${item?.id}`)
        },
      },
      {
        label: renderLabelItem(transBook("edit"), "/img/icon/edit.svg", "edit"),
        key: "1",
        onClick: () => props.onEditPost && props.onEditPost(item),
      },
      {
        label: renderLabelItem(transBook("delete"), "/img/icon/trash_outline.svg", "trash_outline"),
        key: "3",
        onClick: () => confirmDelete(),
      }
    ]

    return (
      <DropDownMenu
        className={`${className || ""}`}
        menu={{ items, className: classNames(CustomDropDownMenuCss) }}
        onOpenChange={(open) => handleOpenChange(open, item)}
      />
    )
  }

  return (
    <Card
      key={props.keyProps}
      cover={
        <div className="overflow-hidden relative group rounded-t-[8px]">
          <Link
            target={props?.target}
            aria-label="News detail"
            href={`${props?.url || "#"}`}
            className="absolute w-full h-full z-10 top-0 left-0"></Link>
          <Image
            src={`${props?.url_image || "/img/default_image.jpg"}`}
            alt={`${props?.alt_image || "no-image"}`}
            width={300}
            height={300}
            className="w-full group-hover:scale-110 transition-transform duration-300 ease-in-out aspect-[3/2]"
          />
          {props?.isButtonTopRight
            ? buttonTopRight(props?.item, "absolute top-[6px] right-[6px]")
            : props.showMark && (
                <button
                  onClick={() => handleButtonClick(props.keyProps)}
                  className={`absolute top-[12px] right-[16px] w-[42px] h-[42px] rounded-lg flex justify-center items-center z-[11] hover:opacity-80 ${
                    activeButtons.includes(props.keyProps) ? "bg-[var(--primary--70)]" : "bg-[var(--secondary-10)]"
                  }`}>
                  <Image
                    src={activeButtons.includes(props.keyProps) ? "/img/icon/bookmark_ed.svg" : "/img/icon/bookmark.svg"}
                    alt={"bookmap"}
                    width={24}
                    height={24}
                  />
                </button>
              )}
        </div>
      }
      className={classNames(`shadow-lg relative ${props?.className || ""}`, ItemNewsCss)}>
      <Link
        target={props?.target}
        aria-label="News detail"
        href={`${props?.url || "#"}`}
        className="my-0 line-clamp-2 text-[16px] leading-[20px] h-[42px] text-[var(--secondary-100)] font-medium hover:underline">
        {props?.title}
      </Link>
      <p
        className="text-sm mt-1 mb-6 line-clamp-3 font-light h-[60px] text-[var(--secondary-70)]"
        dangerouslySetInnerHTML={{ __html: props?.decs || "" }}></p>
      <p className="font-light text-[var(--secondary-50)] text-xs m0">
        <span>{`${dayjs.unix(props?.createdAt).format("MMM DD, YYYY") || ""}`}</span>
        <span>{`${(props?.author && " | ") || ""}${props?.author || ""}`}</span>
      </p>
      {modalContextHolder}
    </Card>
  )
}
