"use client"
import { Button as ButtonRAC } from "react-aria-components"
import { useMediaQuery } from "usehooks-ts"

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

import { trpc } from "@/lib/trpc/client"
import { useRatesStore } from "@/stores/select-rate"

import { useRoomContext } from "@/contexts/SelectRate/Room"
import useLang from "@/hooks/useLang"

import RoomPackageFilterModal from "./Modal"
import RoomPackageFilterPopover from "./Popover"
import { getIconNameByPackageCode } from "./utils"

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

import type { PackageEnum } from "@/types/requests/packages"

export default function RoomPackageFilter() {
  const lang = useLang()
  const utils = trpc.useUtils()
  const displayAsPopover = useMediaQuery("(min-width: 768px)")

  const {
    actions: { removeSelectedPackage, updateRooms },
    bookingRoom,
    selectedPackages,
  } = useRoomContext()
  const booking = useRatesStore((state) => state.booking)

  async function deleteSelectedPackage(code: PackageEnum) {
    removeSelectedPackage(code)
    const filterRates = await utils.hotel.availability.selectRate.room.fetch({
      booking: {
        fromDate: booking.fromDate,
        hotelId: booking.hotelId,
        searchType: booking.searchType,
        toDate: booking.toDate,
        room: {
          ...bookingRoom,
          bookingCode: bookingRoom.rateCode
            ? bookingRoom.bookingCode
            : booking.bookingCode,
          packages: selectedPackages
            .filter((pkg) => pkg.code !== code)
            .map((pkg) => pkg.code),
        },
      },
      lang,
    })
    updateRooms(filterRates?.roomConfigurations)
  }

  return (
    <div className={styles.roomPackageFilter}>
      <div className={styles.selectedPackages}>
        {selectedPackages.map((pkg) => (
          <Typography
            key={pkg.code}
            variant="Body/Supporting text (caption)/smRegular"
          >
            <span className={styles.selectedPackage}>
              <MaterialIcon
                icon={getIconNameByPackageCode(pkg.code)}
                size={16}
                color="CurrentColor"
              />
              {pkg.description}
              <ButtonRAC
                onPress={() => deleteSelectedPackage(pkg.code)}
                className={styles.removeButton}
              >
                <MaterialIcon icon="close" size={16} color="CurrentColor" />
              </ButtonRAC>
            </span>
          </Typography>
        ))}
      </div>
      <div hidden={displayAsPopover}>
        <RoomPackageFilterModal />
      </div>
      <div hidden={!displayAsPopover}>
        <RoomPackageFilterPopover />
      </div>
    </div>
  )
}
