"use client"

import React, { useEffect, useMemo, useState } from "react"
import { Popover, Table } from "antd"
import Image from "next/image"
import { SOURCE_CONTACT } from "@/config/constant"
import { renderTooltipText } from "@component/Common/TooltipText"
import { formatDuration } from "@/util/Common"
import { useRecoilState, useRecoilValue } from "recoil"
import { activeMusicCategoryState, songPlayingState, typePlayMusicState } from "@/recoil"
import NotFoundBox from "@/component/Notfound"
import { useRouter } from "@/i18n/routing"
import { useTranslations } from "next-intl"
import { LoadMoreInfinite } from "@/component/Common/LoadMoreInfinite"

interface IProps {
  dataSourceMusic: any
  isLoading: boolean
  isNextPage: boolean
  hasNextPage: boolean
  fetchNextPage: () => void
}

const TableMusic = (props: IProps) => {
  const router = useRouter()
  const trans = useTranslations("music")
  const [widthCol, setWidthCol] = useState<number>(250)
  const [songPlaying, setSongPlaying] = useRecoilState(songPlayingState)
  const [defaulPlay, setDefaulPlay] = useRecoilState(typePlayMusicState)
  const albumSelected = useRecoilValue(activeMusicCategoryState)

  const widthNumber = useMemo(() => (props?.dataSourceMusic?.length > 99 ? "w-12" : "w-10"), [props?.dataSourceMusic?.length])

  useEffect(() => {
    const updateTabPosition = () => {
      setWidthCol(window.innerWidth >= 1600 ? 300 : window.innerWidth >= 768 ? 250 : 200)
    }
    updateTabPosition()
    window.addEventListener("resize", updateTabPosition)

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

  const handleRowClick = (record: any) => {
    setSongPlaying(record)
    setDefaulPlay((prevState) => ({
      ...prevState,
      iconPause: "/img/icon/ms_play.svg",
      isPause: true,
    }))
  }

  const columns: any = useMemo(
    () => [
      {
        key: "stt",
        dataIndex: "stt",
        align: "center",
        className: "!p-0",
        width: widthCol,
        ellipsis: {
          showTitle: false,
        },
        render: (_: any, record: any, index: number) => {
          return (
            <div className="flex py-4">
              <div className={`text-base leading-[22px] text-[var(--secondary-100)] font-normal px-2.5 py-[11px] text-left ${widthNumber}`}>{index + 1}</div>
              <div
                className="mr-2 w-[42px] flex items-center justify-center"
                onClick={() => {
                  console.log("record", record?.id)
                }}>
                <Image
                  src={`/img/icon/${songPlaying?.id === record?.id && defaulPlay?.isPause ? "ms_playing" : "ms_pauseing"}.svg`}
                  alt={"heart"}
                  width={42}
                  height={42}
                  className="aspect-square"
                />
              </div>
              <div
                className="mr-2 w-[50px] flex items-center justify-center"
                onClick={() => {
                  console.log("record", record?.id)
                }}>
                <Image
                  src={record?.poster}
                  alt=""
                  width={50}
                  height={50}
                  className="aspect-square rounded-lg"
                  onError={(e) => (e.currentTarget.src = "/img/default_image.jpg")}
                />
              </div>
              {renderTooltipText(record?.title, "text-left", "flex-1")}
            </div>
          )
        },
      },
      {
        dataIndex: "description",
        key: "description",
        className: "!px-0 !py-4",
        align: "center",
        minWidth: 200,
        ellipsis: true,
        render: (description: string) => {
          return (
            <div className="px-2.5">
              <Popover
                title=""
                content={
                  <div
                    className="max-h-32 text-base overflow-y-auto"
                    dangerouslySetInnerHTML={{ __html: description || "" }}></div>
                }>
                <div
                  className="h-[25px] line-clamp-1 text-base overflow-hidden"
                  dangerouslySetInnerHTML={{ __html: description || "" }}></div>
              </Popover>
            </div>
          )
        },
      },
      {
        dataIndex: "duration",
        key: "duration",
        align: "right",
        className: "!p-0",
        width: 91,
        render: (timer: number) => (
          <div className="flex py-4 px-2.5 text-sm font-light text-black items-center justify-end">
            <div className="mr-2 w-[24px] flex items-center justify-center">
              <Image
                src={`/img/icon/clock.svg`}
                alt={"clock"}
                width={24}
                height={24}
                className="aspect-square"
              />
            </div>
            <div>{timer ? formatDuration(timer) : "--:--"}</div>
          </div>
        ),
      },
    ],
    [props?.dataSourceMusic, songPlaying, defaulPlay, SOURCE_CONTACT],
  )

  return (
    <div className="flex-1 min-w-0 h-full overflow-y-auto">
      <Table
        showHeader={false}
        rowKey={"id"}
        columns={columns}
        dataSource={props?.dataSourceMusic || []}
        pagination={false}
        scroll={{ y: 490 }}
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
        })}
        className="flex-1"
        locale={{
          emptyText: (
            <NotFoundBox
              className="!bg-white py-8 rounded-3xl"
              backHome={false}
              message={trans("we_found_nothing_here")}
              slot={
                <button
                  type="button"
                  onClick={() => {
                    router.push(`/music/${albumSelected}`)
                  }}
                  className="text-center inline-block w-full underline font-medium lg:text-lg">
                  {trans("add_songs_to_album")}
                </button>
              }
            />
          ),
        }}
      />

      <LoadMoreInfinite
        isLoading={props?.isLoading}
        isNextPage={props?.isNextPage}
        hasNextPage={props?.hasNextPage}
        fetchNextPage={props?.fetchNextPage}
      />
    </div>
  )
}

export default TableMusic
