"use client"

import { BackgroundColor, Section } from '@/components/Section/Section'
import { StaticImageData } from 'next/image'
import { ImageWithText } from '@/compositions/ImageWithText/ImageWithText'
import { CollapsibleArrow } from '@/components/CollapsibleArrow/CollapsibleArrow'
import React, { useEffect, useRef, useState } from 'react'
import { Container } from '@/components/Container/Container'
import styles from "./styles.module.scss"
import classNames from 'classnames'

type ImageWithTextProps = {
  backgroundColor?: BackgroundColor,
  title: string,
  image: StaticImageData | string,
  text: string
  schema?: 'base' | 'contrast'
  content: React.ReactNode
}

type MoreInformationProps = {
  isCollapsed: boolean,
  onClick: () => void
}

const MoreInformation = ({isCollapsed, onClick}: MoreInformationProps) => {
  const [direction, setDirection] = useState<"UP" | "DOWN">(isCollapsed ? "DOWN" : "UP")

  const toggleDirection = () => {
    setDirection(direction == "UP" ? "DOWN" : "UP")
  }

  const handleClick = () => {
    toggleDirection();
    onClick();
  }

  return (
    <button
      onClick={handleClick}
      className={styles.more}
      onMouseEnter={toggleDirection}
      onMouseLeave={toggleDirection}
    >Mehr erfahren <CollapsibleArrow direction={direction}/></button>
  )
};

export const CollapsibleImageWithText = ({backgroundColor, title, image, text, schema, content}: ImageWithTextProps) => {

  const ref = useRef<HTMLDivElement>(null)
  const ref2 = useRef<HTMLDivElement>(null)
  const [contentHeight, setContentHeight] = useState(0)
  const [isCollapsed, setIsCollapsed] = useState(true)

  const collapse = () => {
    setIsCollapsed(true)
    ref.current?.scrollIntoView({'behavior': 'smooth'})
  }

  useEffect(() => {
    if (ref2.current) {
      setContentHeight(ref2.current.scrollHeight)
    }
  }, [ref2])

  return (
    <div ref={ref}>
      <ImageWithText
        title={title}
        image={image}
        text={text}
        schema={schema}
        backgroundColor={backgroundColor}
        unoptimized={false}
        opaque={true}
        link={<MoreInformation isCollapsed={isCollapsed} onClick={() => setIsCollapsed(!isCollapsed)} />}
      />

      <div
        ref={ref2}
        className={classNames({
        [styles.content]: true,
      })}
        style={{maxHeight: isCollapsed ? undefined : contentHeight}}
      >
        <Section
          backgroundColor={backgroundColor}
          padding={"small"}
          paddingBottom={"large"}
        >
          <Container>
            {content}
          </Container>

          <div className={styles.endButton}>
            <CollapsibleArrow direction={"UP"} onClick={collapse}/>
          </div>
        </Section>
      </div>
    </div>

  )
}