"use client"

import { Dispatch, SetStateAction, useEffect, useState } from "react"
import { Button, Modal, type MenuProps } from "antd"
import Image from "next/image"
import { useTranslations } from "next-intl"
import { CustomDropDownMenuCss, DropDownMenu } from "@/component/Common/DropDownMenu"
import classNames from "classnames"

import { Swiper, SwiperSlide } from "swiper/react"
import "swiper/css"
import "swiper/css/navigation"
import { Mousewheel, Navigation } from "swiper/modules"
import { SwiperCss } from "./style"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faPlus, faChevronRight, faChevronLeft } from "@fortawesome/free-solid-svg-icons"
import CardItemCategory from "@/component/Common/CardItemCategory"
import { floor } from "lodash"
import { IMusicAlbums } from "@/type/Music"
import { useRouter } from "@/i18n/routing"
import { useDeleteAlbum } from "@/hook/useMusic"
import { useNotificationContext } from "@/component/Layout/NotificationContext"
import { renderLabelItem } from "@/component/Common/LabelItem"
import { LoadingBox } from "@/component/Common/LoadingBox"
import AlbumShare from "@/component/Common/AlbumShare"

interface IProps {
  dataSource: IMusicAlbums[]
  keyActiveMusicCategory: string | number
  setKeyActiveMusicCategory: Dispatch<SetStateAction<string | number>>
  isLoading?: boolean
  isNextPage?: boolean
  hasNextPage?: boolean
  userShares: string[]
  fetchNextPage: () => void
  onShare: (album: string, user: string) => void
}

export const SwiperMusicCategory = (props: IProps) => {
  const router = useRouter()
  const { notify } = useNotificationContext()
  const [modal, modalContextHolder] = Modal.useModal()
  
  const trans = useTranslations("music")
  const transBook = useTranslations("book")
  const transButton = useTranslations("button")
  const transMessage = useTranslations("message")
  const transGeneral = useTranslations("general")

  const [swiperRef, setSwiperRef] = useState(null as any)
  const [keySelect, setKeySelect] = useState<any>("")
  const [itemSlide, setItemSlide] = useState(2)
  const [showPrev, setShowPrev] = useState(false)
  const [loading, setLoading] = useState(true)
  const [openShare, setOpenShare] = useState(false)
  const [albumSelected, setAlbumSelected] = useState<any>(null)

  const deleteAlbum = useDeleteAlbum()

  useEffect(() => {
    setLoading(true)
    setTimeout(() => {
      setLoading(false)
    }, 300)
  }, [])

  const swiperMargin = showPrev ? "!mx-5 md:!mx-8 lg:!mx-[2.375rem]" : "!mr-5 md:!mr-8 lg:!mr-[2.375rem]"

  const handleSlideChange = (swiper: any) => {
    setShowPrev(swiper.activeIndex > 0)
  }

  const prevHandler = () => {
    swiperRef.slidePrev()
  }

  const nextHandler = () => {
    swiperRef.slideNext()
  }



  const handleDeleteAlbum = () => {
    deleteAlbum
      .mutateAsync(keySelect)
      .then((res: any) => {
        if (res?.status === 200) {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: transGeneral("deleted_successfully"),
          })
        }
      })
      .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() {
        handleDeleteAlbum()
      },
    })
  }

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

  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(`/music/edit-album/${item?.id}`)
        },
      },
      {
        label: renderLabelItem(transBook("edit"), "/img/icon/edit.svg", "edit"),
        key: "1",
        onClick: () => {
          router.push(`/music/edit-album/${item?.id}`)
        },
      },
      {
        label: renderLabelItem("Share", "/img/icon/redo.svg", "Share"),
        key: "3",
        onClick: () => setOpenShare(true),
      },
      {
        label: renderLabelItem(transBook("delete"), "/img/icon/trash_outline.svg", "trash_outline"),
        key: "4",
        onClick: () => confirmDelete(),
      },
    ]

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

  const handleClick = (key: string | number) => {
    props?.setKeyActiveMusicCategory(key)
  }

  useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth

      switch (true) {
        case width >= 1280:
          setItemSlide(floor(width / 176))
          break
        case width >= 768:
          setItemSlide(3)
          break
        default:
          setItemSlide(2)
      }
    }

    handleResize()

    window.addEventListener("resize", handleResize)

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

  return loading ? (
    <div className="bg-gray-200 rounded-lg animate-pulse h-32 mb-6">
      <LoadingBox />
    </div>
  ) : (
    <div className="flex">
      {props?.dataSource?.length ? (
        <div className="relative flex overflow-hidden mb-3 grow">
          {props?.dataSource?.length > itemSlide && (
            <>
              <button
                aria-label="prev"
                onClick={prevHandler}
                className={classNames(
                  `cursor-pointer flex text-[var(--secondary-100)] bg-[var(--primary--20)] shadow-xl h-full w-5 md:w-8 lg:w-[2.375rem] border-none z-30 transition-opacity duration-300 ease-in-out items-center justify-center absolute text-center left-0 my-auto text-[16px] shadow-gray-500/50 top-0
                ${showPrev ? "opacity-100" : "opacity-0 pointer-events-none"}`,
                )}>
                <FontAwesomeIcon
                  icon={faChevronLeft}
                  className="max-h-[16px]"
                />
              </button>
              <button
                aria-label="next"
                onClick={nextHandler}
                className={classNames(
                  "cursor-pointer flex text-[var(--secondary-100)] bg-[var(--primary--20)] shadow-xl h-full w-5 md:w-8 lg:w-[2.375rem] border-none z-30 transition-opacity duration-300 ease-in-out items-center justify-center absolute text-center right-0 my-auto text-[16px] shadow-gray-500/50 top-0",
                )}>
                <FontAwesomeIcon
                  icon={faChevronRight}
                  className="max-h-[16px]"
                />
              </button>
            </>
          )}
          <Swiper
            breakpoints={{
              992: {
                spaceBetween: 12,
              },
              1280: {
                spaceBetween: 16,
              },
            }}
            slidesPerView="auto"
            spaceBetween={8}
            mousewheel={{
              forceToAxis: true,
              releaseOnEdges: true,
              sensitivity: 0,
            }}
            onReachEnd={() => {
              if (!props?.isLoading && props?.hasNextPage && props?.isNextPage) props?.fetchNextPage()
            }}
            onSwiper={(swiper: any) => setSwiperRef(swiper)}
            navigation={true}
            onSlideChange={handleSlideChange}
            onInit={handleSlideChange}
            modules={[Navigation, Mousewheel]}
            className={classNames(`flex flex-1 transition-all duration-300 ease-in-out ${swiperMargin}`, SwiperCss)}>
            {props?.dataSource?.map((item: IMusicAlbums) => (
              <SwiperSlide
                key={item?.id}
                className="!w-[9.625rem]">
                <CardItemCategory
                  key={item?.id}
                  keyProps={item?.id}
                  keySelect={keySelect}
                  keyActive={props?.keyActiveMusicCategory}
                  onClick={handleClick}
                  type={"default"}
                  url_image={item?.cover}
                  alt_image={item?.title}
                  classNameImage="rounded-lg"
                  classNameBox="group"
                  title={item?.title}
                  decs={`${item?.items_num} ${item?.items_num > 1 ? trans("songs") : trans("song")}`}
                  buttonTopRight={buttonTopRight(item, "absolute top-[6px] right-[6px] hidden group-hover:flex")}
                />
              </SwiperSlide>
            ))}
          </Swiper>
        </div>
      ) : null}
      <div className={`ml-0 w-full xs:ml-4 xs:w-[4.5rem] md:w-[7.5rem] lg:w-[10.5rem] mb-3`}>
        <Button
          onClick={() => router.push("/music/create-album")}
          type="dashed"
          className={`w-full !px-1 xs:!px-3.5 xs:w-[4.5rem] md:w-[7.5rem] lg:w-[10.5rem] min-h-28 !h-full !flex flex-col text-base leading-[22px] font-normal text-[var(--secondary-100)]`}>
          <FontAwesomeIcon icon={faPlus} />
          <span className="break-words whitespace-normal">{trans("news_albums")}</span>
        </Button>
      </div>
      <AlbumShare
        isOpen={openShare}
        album={albumSelected}
        userShares={props.userShares}
        setOpen={setOpenShare}
        onShare={props.onShare}
        imageClassName="aspect-square !h-72 !w-72"
      />
      {modalContextHolder}
    </div>
  )
}
