"use client"

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

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

import SectionContainer from "@/components/Section/Container"
import ShowMoreButton from "@/components/TempDesignSystem/ShowMoreButton"

import { RoomCard } from "./RoomCard"

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

import type { RoomsProps } from "@/types/components/hotelPage/room"
import { HotelHashValues } from "@/types/enums/hotelPage"

export function Rooms({ heading, rooms, preamble }: RoomsProps) {
  const showToggleButton = rooms.length > 3
  const [allRoomsVisible, setAllRoomsVisible] = useState(!showToggleButton)
  const sortedRooms = useMemo(() => {
    return rooms.sort((a, b) => a.sortOrder - b.sortOrder)
  }, [rooms])

  const scrollRef = useRef<HTMLDivElement>(null)

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

  return (
    <SectionContainer
      id={HotelHashValues.rooms}
      className={styles.roomsContainer}
    >
      <div ref={scrollRef} className={styles.scrollRef}></div>
      <header className={styles.sectionHeader}>
        <Typography variant="Title/md">
          <h2 className={styles.heading}>{heading}</h2>
        </Typography>
        {preamble && (
          <Typography variant="Body/Paragraph/mdRegular">
            <p>{preamble}</p>
          </Typography>
        )}
      </header>
      <ul
        className={cx(styles.roomsList, {
          [styles.allVisible]: allRoomsVisible,
        })}
      >
        {sortedRooms.map((room) => (
          <li className={styles.roomsItem} key={room.id}>
            <RoomCard room={room} />
          </li>
        ))}
      </ul>

      {showToggleButton ? (
        <ShowMoreButton
          loadMoreData={handleShowMore}
          showLess={allRoomsVisible}
        />
      ) : null}
    </SectionContainer>
  )
}
