"use client"

import { cx } from "class-variance-authority"
import { useRef, useState } from "react"
import { useIntl } from "react-intl"

import { Typography } from "@scandic-hotels/design-system/Typography"

import { FacilityIcon } from "@/components/SidePeeks/RoomSidePeek/facilityIcon"
import ShowMoreButton from "@/components/TempDesignSystem/ShowMoreButton"

import styles from "./roomFacilities.module.css"

import type { Room } from "@/types/hotel"

interface RoomFacilitiesProps {
  roomFacilities: Room["roomFacilities"]
}

export default function RoomFacilities({
  roomFacilities,
}: RoomFacilitiesProps) {
  const intl = useIntl()
  const showMobileToggleButton = roomFacilities.length > 10
  const [allVisibleOnMobile, setAllVisibleOnMobile] = useState(
    !showMobileToggleButton
  )
  const scrollRef = useRef<HTMLHeadingElement>(null)

  const mappedFacilities = roomFacilities
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((facility) => {
      const facilityName = facility.availableInAllRooms
        ? facility.name
        : intl.formatMessage(
            {
              defaultMessage: "{facility} (available in some rooms)",
            },
            {
              facility: facility.name,
            }
          )
      return {
        ...facility,
        name: facilityName,
      }
    })

  function handleShowMore() {
    if (scrollRef.current && allVisibleOnMobile) {
      scrollRef.current.scrollIntoView({ behavior: "smooth" })
    }
    setAllVisibleOnMobile((state) => !state)
  }

  return (
    <>
      <Typography variant="Title/Subtitle/md">
        <h3 ref={scrollRef} className={styles.heading}>
          {intl.formatMessage({
            defaultMessage: "Room amenities",
          })}
        </h3>
      </Typography>
      <ul
        className={cx(styles.facilities, {
          [styles.allVisibleMobile]: allVisibleOnMobile,
        })}
      >
        {mappedFacilities.map((facility) => (
          <li
            className={styles.item}
            key={`${facility.name}_${facility.sortOrder}`}
          >
            <FacilityIcon
              name={facility.icon}
              size={24}
              color="CurrentColor"
              className={styles.icon}
            />
            <Typography variant="Body/Paragraph/mdRegular">
              <span>{facility.name}</span>
            </Typography>
          </li>
        ))}
      </ul>
      {showMobileToggleButton ? (
        <div className={styles.ctaWrapper}>
          <ShowMoreButton
            loadMoreData={handleShowMore}
            showLess={allVisibleOnMobile}
          />
        </div>
      ) : null}
    </>
  )
}
