import {
  getOpeningHours,
  getPrettyOpeningHoursForFunction,
  PrettyOpeningHours,
} from "@/lib/openinghours";
import styles from "./openingHoursSectionBlock.module.scss";
import { Fragment } from "react";

function OpeningHoursSubsection({
  title,
  prettyHours,
}: {
  title: string;
  prettyHours: PrettyOpeningHours[];
}) {
  return (
    <section className={styles.openingHoursSubsection}>
      <h3>{title}</h3>
      <table className="openingHours">
        <tbody>
          {prettyHours.map(({ range, time, custom }) => (
            <tr key={range}>
              <td className={styles.dayRange}>{range}</td>
              <td>
                {time && <span className={styles.timeRange}>{time}</span>}
                {custom && <span className={styles.timeRange}>{custom}</span>}
                {!time && !custom && <span className={styles.closed}>Stengt</span>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

export async function OpeningHoursSectionBlock() {
  const allOpeningHours = await getOpeningHours();
  const subsections = [
    ["glassbaren", "Glassbaren"],
    ["bokcafeen", "Bokcaféen"],
    ["ekspedisjonen", "Ekspedisjonen"],
  ];
  const { announcement } = allOpeningHours;

  return (
    <section className={styles.openingHoursSection}>
      {announcement && <p>{announcement}</p>}
      <div className={styles.openingHoursList}>
        {subsections.map((subsection) => {
          const [slug, title] = subsection;
          const prettyHours = getPrettyOpeningHoursForFunction(
            allOpeningHours,
            slug
          );
          if (!prettyHours || prettyHours?.length === 0) {
            return <></>;
          }
          return (
            <OpeningHoursSubsection
              key={slug}
              title={title}
              prettyHours={prettyHours}
            />
          );
        })}
      </div>
    </section>
  );
}
