"use client"

import { useState } from "react"

import { Carousel } from "@/components/Carousel"
import ContentCard from "@/components/ContentCard"
import SectionContainer from "@/components/Section/Container"
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 { CarouselCardsProps } from "@/types/components/blocks/carouselCards"

export default function CarouselCards({ carousel_cards }: CarouselCardsProps) {
  const {
    heading,
    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 (
    <SectionContainer>
      <SectionHeader
        title={heading}
        headingLevel="h2"
        headingAs="h3"
        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" />
    </SectionContainer>
  )
}
