import { ChevronDown } from "react-feather"

import Title from "@scandic-hotels/design-system/Title"

import {
  findAvailableRewards,
  getGroupedLabelAndDescription,
  getGroupedRewards,
} from "@/utils/loyaltyTable"

import RewardValue from "../RewardValue"
import DesktopHeader from "./DesktopHeader"

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

import type {
  LargeTableProps,
  RewardTableHeaderProps,
} from "@/types/components/overviewTable"

export default function LargeTable({
  levels,
  activeLevel,
  Select,
}: LargeTableProps) {
  const keyedGroupedRewards = getGroupedRewards(levels)

  return (
    <table className={styles.table}>
      <DesktopHeader
        levels={levels}
        activeLevel={activeLevel}
        Select={Select}
      />
      <tbody className={styles.tbody}>
        {Object.entries(keyedGroupedRewards).map(
          ([key, groupedRewards], idx) => {
            const { label, description } =
              getGroupedLabelAndDescription(groupedRewards)

            return (
              <tr key={key + idx} className={styles.tr}>
                <th scope={"row"} className={styles.rewardTh}>
                  <RewardTableHeader name={label} description={description} />
                </th>
                {levels.map((level, idx) => {
                  const rewardIdsInGroup = groupedRewards.map(
                    (b) => b.reward_id
                  )
                  const reward = findAvailableRewards(rewardIdsInGroup, level)
                  return (
                    <td
                      key={`${reward?.reward_id}-${idx}`}
                      className={styles.td}
                    >
                      <RewardValue reward={reward} />
                    </td>
                  )
                })}
              </tr>
            )
          }
        )}
      </tbody>
    </table>
  )
}

function RewardTableHeader({ name, description }: RewardTableHeaderProps) {
  return (
    <details className={styles.details}>
      <summary className={styles.summary}>
        <hgroup className={styles.rewardHeader}>
          <Title as="h4" level="h2" textTransform={"regular"}>
            {name}
          </Title>
          <span className={styles.chevron}>
            <ChevronDown />
          </span>
        </hgroup>
      </summary>
      <p
        className={styles.rewardDescription}
        dangerouslySetInnerHTML={{ __html: description }}
      />
    </details>
  )
}
