"use client"
import { motion } from "motion/react"
import { assign } from "radash"
import React, { ComponentPropsWithoutRef, ElementRef, forwardRef } from "react"
import { useCallbackRef, useDimensions } from "../../hooks"
import { Block } from "../Block"

export type AnimateHeightProps = {
  children: React.ReactNode
  className?: string
} & ComponentPropsWithoutRef<typeof motion.div>

export const AnimateHeight = forwardRef<
  ElementRef<typeof motion.div>,
  AnimateHeightProps
>(function AnimateHeight({ children, className, animate, ...rest }, ref) {
  const [childRef, setChildRef] = useCallbackRef<HTMLDivElement>()
  const { height: childHeight } = useDimensions(childRef)

  return (
    <motion.div
      animate={
        childRef.current
          ? assign(
              { height: childHeight },
              typeof animate === "object" ? animate : {},
            )
          : undefined
      }
      className={className}
      initial={false}
      ref={ref}
      transition={{ type: "spring", bounce: 0, duration: 0.3 }}
      {...rest}
    >
      <Block asChild ref={setChildRef}>
        {children}
      </Block>
    </motion.div>
  )
})
