"use client"

import React, { useEffect, useMemo, useState } from "react"
import { find } from "lodash"
import { useTranslations } from "next-intl"
import type { MenuProps } from "antd"
import Image from "next/image"
import classNames from "classnames"
import { useRecoilValue } from "recoil"

import CardItemKuisine from "../ItemKuisine"
import HeaderBreadcrumb from "@/component/Layout/HeaderBreadcrumb"
import { useRouter } from "@/i18n/routing"
import { PAGINATION, kuisineOptions } from "@/config/constant"
import { typeKuisineState } from "@/recoil"
import { CustomDropDownMenuCss, DropDownMenu } from "@/component/Common/DropDownMenu"
import { useGetKuisineBookings } from "@/hook/useKuisine"
import { LoadingResult } from "@/component/Common/LoadingResult/LoadingResult"
import { renderLabelItem } from "@/component/Common/LabelItem"

const MyBookings = () => {
  const router = useRouter()
  const options = kuisineOptions()
  const typeKuisine = useRecoilValue(typeKuisineState)

  const trans = useTranslations("kuisine")
  const transBook = useTranslations("book")
  const transButton = useTranslations("button")

  const [searchValue, setSearchValue] = useState("")
  const [activeButtons, setActiveButtons] = useState<any>("")
  const [page, setPage] = useState(PAGINATION.DEFAULT_CURRENT_PAGE)
  const [totalPage, setTotalPage] = useState(0)
  const [query, setQuery] = useState({ pageNum: page, pageSize: PAGINATION.DEFAULT_PAGE_SIZE })

  const { data: kuisinesBookings, isLoading } = useGetKuisineBookings(query)

  const dataKuisinesBookings = useMemo(() => {
    setTotalPage(kuisinesBookings?.data?.total_pages || 0)

    return kuisinesBookings?.data?.bookings
  }, [kuisinesBookings?.data?.bookings, kuisinesBookings?.data?.total_pages])

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

  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(`/kuisine/${item?.kuisine?.category?.id}/${item?.kuisine?.id}`)
        },
      }
    ]

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

  const renderLabelContent = (title: string, src_icon: string, alt_icon: string) => {
    return (
      <div className={`text-sm flex items-center font-normal	text-[var(--secondary-100)] py-2.5`}>
        <Image
          src={src_icon}
          alt={alt_icon}
          width={24}
          height={24}
        />
        <div className="pl-1.5 flex-1">{title}</div>
      </div>
    )
  }

  const handleScroll = (e: any) => {
    const { scrollTop, scrollHeight, clientHeight } = e.target
    if (scrollTop + clientHeight >= scrollHeight - 5) {
      if (page < totalPage && !isLoading) {
        setPage(page + 1)
        setQuery({ ...query, pageNum: page + 1 })
      }
    }
  }

  useEffect(() => {
    const mainElement = document.getElementById("layout-content")

    const handleScroll = () => {
      if (mainElement) {
        const { scrollTop, scrollHeight, clientHeight } = mainElement
        if (scrollTop + clientHeight >= scrollHeight - 5) {
          if (page < totalPage && !isLoading) {
            setPage(page + 1)
            setQuery({ ...query, pageNum: page + 1 })
          }
        }
      }
    }

    if (mainElement) {
      mainElement.addEventListener("scroll", handleScroll)
    }

    return () => {
      if (mainElement) {
        mainElement.removeEventListener("scroll", handleScroll)
      }
    }
  }, [])

  return (
    <div className="h-full flex flex-col">
      <HeaderBreadcrumb
        items={[
          {
            aria_label: find(options, { value: typeKuisine as string })?.label || "",
            href: "#",
            title: find(options, { value: typeKuisine as string })?.label || "",
          },
        ]}
        subtitle={`${dataKuisinesBookings?.length || 0} ${dataKuisinesBookings && dataKuisinesBookings?.length > 0 ? trans("kuisines") : trans("kuisine")}`}
        showButton={false}
      />
      <LoadingResult
        isLoading={isLoading && !dataKuisinesBookings?.length}
        isShowResult={Boolean(dataKuisinesBookings?.length)}
        result={
          <div
            className="overflow-y-auto"
            onScroll={handleScroll}>
            <div
              key={"dataKuisinesBookings"}
              className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2 p-4">
              {dataKuisinesBookings?.map((item: any) => (
                <CardItemKuisine
                  key={item?.kuisine?.id}
                  keyProps={item?.kuisine?.id}
                  keyActive={activeButtons}
                  className="col-span-1 flex md:block !border-b-0 !rounded-b-[0px]"
                  type={item?.kuisine?.type}
                  url={`/kuisine/${item?.kuisine?.category?.id}/${item?.kuisine?.id}`}
                  url_image={item?.kuisine?.picture1}
                  alt_image={item?.kuisine?.picture1_org_name}
                  classNameImage="rounded-lg"
                  title={item?.kuisine?.recipe}
                  decs={item?.kuisine?.description}
                  nation={item?.kuisine?.theme}
                  foodType={item?.kuisine?.seatingtype}
                  classNameDecs="!mb-0"
                  buttonTopRight={buttonTopRight(item, "absolute top-[6px] right-[6px]")}
                  paymentElement={
                    <div className={`mb-3 flex items-center`}>
                      <Image
                        alt="payment_success"
                        src="/img/icon/payment_success.svg"
                        width={40}
                        height={40}
                      />
                      <p className="text-[var(--kuisine--payment-success)] text-sm font-semibold pl-2">{trans("payment_successful")}</p>
                    </div>
                  }
                  footer={
                    <div
                      className={`flex justify-between shrink-0 px-4 rounded-lg border border-solid !border-t-0 !rounded-t-[0px]
                      ${activeButtons === item?.kuisine?.id ? "border-[var(--primary--70)] bg-[var(--primary--30)]" : "bg-white border-[var(--secondary-20)]"}
                    `}>
                      {renderLabelContent(`${item?.kuisine?.ratings?.average || 0} km`, "/img/icon/routing.svg", "routing")}
                      {renderLabelContent(`${item?.kuisine?.key || 0} hours`, "/img/icon/timer.svg", "timer")}
                      {renderLabelContent(`${item?.seats} ${trans("seats")}`, "/img/icon/user_tag.svg", "user_tag")}
                    </div>
                  }
                />
              ))}
            </div>
            {/* <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2 p-4">
          {dataSource?.map((item: any) => (
            <CardItemKuisine
              keyProps={item?.key}
              keyActive={activeButtons}
              className="col-span-1 flex md:block !border-b-0 !rounded-b-[0px]"
              type={item?.type}
              url={`/kuisine/${id}/${item?.key}`}
              url_image={item?.url_image}
              alt_image={item?.alt_image}
              classNameImage="rounded-lg"
              title={item?.title}
              decs={item?.decs}
              nation={item?.location}
              foodType={item?.foodType}
              classNameDecs="!mb-0"
              buttonTopRight={buttonTopRight(item?.key, "absolute top-[6px] right-[6px]")}
              paymentElement={
                <div className={`mb-3 flex items-center`}>
                  <Image
                    alt="payment_success"
                    src="/img/icon/payment_success.svg"
                    width={40}
                    height={40}
                  />
                  <p className="text-[var(--kuisine--payment-success)] text-sm font-semibold pl-2">Payment Successful</p>
                </div>
              }
              footer={
                <div
                  className={`flex justify-between px-4 rounded-lg border border-solid !border-t-0 !rounded-t-[0px]
                  ${activeButtons === item?.key ? "border-[var(--primary--70)] bg-[var(--primary--30)]" : "bg-white border-[var(--secondary-20)]"}
                `}>
                  {renderLabelContent(`${item?.rate?.toFixed(1)} km`, "/img/icon/routing.svg", "routing")}
                  {renderLabelContent(`${item?.key} hours`, "/img/icon/timer.svg", "timer")}
                  {renderLabelContent(`${item?.seats} seats`, "/img/icon/user-tag.svg", "user_tag")}
                </div>
              }
            />
          ))}
        </div> */}
          </div>
        }
      />
    </div>
  )
}

export default MyBookings
