import React, { useEffect, useState } from "react";

import { Button } from "@/components/Button";
import MerchItem, { MerchItemProps } from "@/components/MerchItem";

import styles from "./MerchSection.module.css";

export interface MerchSectionProps {
  header: string;
  description: string;
  items: MerchItemProps[];
}

const MerchSection: React.FC<MerchSectionProps> = ({
  header,
  description,
  items,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [itemsToShowCount, setItemsToShowCount] = useState(3);

  useEffect(() => {
    const updateItemsToShowCount = () => {
      if (window.innerWidth <= 729) {
        setItemsToShowCount(2);
      } else {
        setItemsToShowCount(3);
      }
    };

    updateItemsToShowCount();
    window.addEventListener("resize", updateItemsToShowCount);

    return () => {
      window.removeEventListener("resize", updateItemsToShowCount);
    };
  }, []);

  const canToggle = items.length > itemsToShowCount;

  const handleToggle = (): void => {
    setIsExpanded((prev) => !prev);
  };

  return (
    <section className={styles.merchSection}>
      <h2 className={styles.sectionHeader}>{header}</h2>
      <p className={styles.sectionDescription}>{description}</p>
      <div className={styles.merchGrid}>
        {[...items]
          .sort((a, b) => b.stock - a.stock || a.name.localeCompare(b.name))
          .slice(0, isExpanded ? items.length : itemsToShowCount)
          .map((item: MerchItemProps, idx: number) => (
            <MerchItem key={idx} {...item} />
          ))}
      </div>
      {canToggle && (
        <Button className={styles.toggleButton} onClick={handleToggle}>
          {isExpanded ? "See Less" : "See More"}
        </Button>
      )}
    </section>
  );
};

export default MerchSection;
