"use client"

import { useState } from "react"

import { Carousel } from "@/components/Carousel"
import ContentCard from "@/components/ContentCard"
import { Section } from "@/components/Section"
import { SectionHeader } from "@/components/Section/Header"
import SectionLink from "@/components/Section/Link"
import TabFilters from "@/components/TabFilters"

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

import type { CarouselCards as CarouselCardsBlock } from "@scandic-hotels/trpc/types/blocks"
import type { VariantProps } from "class-variance-authority"

import type { headingVariants } from "@/components/Section/Header/headingVariants"

interface CarouselCardsProps
  extends Pick<CarouselCardsBlock, "carousel_cards"> {
  headingLevel?: "h1" | "h2"
  headingTypography?: VariantProps<typeof headingVariants>["typography"]
}
export default function CarouselCards({
  carousel_cards,
  headingLevel = "h2",
  headingTypography = "Title/sm",
}: CarouselCardsProps) {
  const {
    heading,
    preamble,
    enableFilters,
    defaultFilter,
    filterCategories,
    cards,
    link,
  } = carousel_cards

  const [activeFilter, setActiveFilter] = useState(
    enableFilters ? defaultFilter : null
  )

  const filteredCards = !activeFilter
    ? cards
    : cards.filter(
        (card) => "filterId" in card && card.filterId === activeFilter
      )

  return (
    <Section>
      <SectionHeader
        heading={heading}
        preamble={preamble}
        headingLevel={headingLevel}
        typography={headingTypography}
        link={link}
      />
      {filterCategories.length > 0 && activeFilter && (
        <TabFilters
          categories={filterCategories}
          selectedFilter={activeFilter}
          onFilterSelect={setActiveFilter}
        />
      )}
      <Carousel key={activeFilter} className={styles.carousel}>
        <Carousel.Content>
          {filteredCards.map((card, index) => (
            <Carousel.Item key={`${card.heading}-${index}`}>
              <ContentCard
                heading={card.heading}
                image={card.image}
                bodyText={card.bodyText}
                promoText={card.promoText}
                link={card.link}
              />
            </Carousel.Item>
          ))}
        </Carousel.Content>
        <Carousel.Previous className={styles.navigationButton} />
        <Carousel.Next className={styles.navigationButton} />
        <Carousel.Dots />
      </Carousel>
      <SectionLink link={link} variant="mobile" />
    </Section>
  )
}
