"use client"
import { useEffect, useRef } from "react"
import { useIntl } from "react-intl"

import { CheckIcon, ChevronDownIcon } from "@/components/Icons"
import Link from "@/components/TempDesignSystem/Link"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"

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

import { SectionAccordionProps } from "@/types/components/hotelReservation/selectRate/sectionAccordion"

export default function SectionAccordion({
  header,
  isOpen,
  isCompleted,
  label,
  path,
  children,
}: React.PropsWithChildren<SectionAccordionProps>) {
  const intl = useIntl()

  const contentRef = useRef<HTMLDivElement>(null)
  const circleRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const content = contentRef.current
    const circle = circleRef.current
    if (content) {
      if (isOpen) {
        content.style.maxHeight = `${content.scrollHeight}px`
      } else {
        content.style.maxHeight = "0"
      }
    }

    if (circle) {
      if (isOpen) {
        circle.style.backgroundColor = `var(--UI-Text-Placeholder);`
      } else {
        circle.style.backgroundColor = `var(--Base-Surface-Subtle-Hover);`
      }
    }
  }, [isOpen])

  return (
    <section className={styles.wrapper} data-open={isOpen}>
      <div className={styles.iconWrapper}>
        <div
          className={styles.circle}
          data-checked={isCompleted}
          ref={circleRef}
        >
          {isCompleted ? (
            <CheckIcon color="white" height="16" width="16" />
          ) : null}
        </div>
      </div>
      <main className={styles.main}>
        <header className={styles.headerContainer}>
          <div>
            <Footnote
              asChild
              textTransform="uppercase"
              color="uiTextPlaceholder"
            >
              <h2>{header}</h2>
            </Footnote>
            <Subtitle
              type="two"
              className={styles.selection}
              color="highContrast"
            >
              {label}
            </Subtitle>
          </div>
          {isCompleted && !isOpen && (
            <Link href={path} color="burgundy" variant="icon">
              {intl.formatMessage({ id: "Modify" })}{" "}
              <ChevronDownIcon color="burgundy" />
            </Link>
          )}
        </header>
        <div className={styles.content} ref={contentRef}>
          {children}
        </div>
      </main>
    </section>
  )
}
