"use client"
import type { Children, Classname } from "@/core/types/common";
import { useEffect, useRef, useState, type JSX } from "react";
import Image from "next/image";

interface OptionWrapperProps extends Children, Classname {
  title: string;
  subtitle: string;
  contentClassName?: string;
  headerClassName?: string;
  defaultExpanded?: boolean;
  updateTrigger?: any[]; // it's actually the useEffect deps, so it could be anything!
}

export default function OptionWrapper(props: Readonly<OptionWrapperProps>): JSX.Element {
  const content = useRef<HTMLDivElement>(null);
  const [scrollHeight, setScrollHeight] = useState<number>(0);
  const [isExpanded, setExpanded] = useState(props.defaultExpanded || false);

  const expandHandler = () => {
    setExpanded(p => !p)
  }

  useEffect(() => {
    if (content.current) {
      setScrollHeight(content.current.scrollHeight);
    }
  }, [props.updateTrigger || undefined]);

  return (
    <div className={`overflow-hidden ${props.className || ""}`}>
      <div
        onClick={expandHandler}
        className={`cursor-pointer flex items-center justify-between select-none ${props.headerClassName || ""}`}
      >
        <p className={"text-[12px] flex items-center gap-1 text-[#131313]"}>
          {props.title}
          <span className={`${!props.subtitle ? "hidden" : ""} text-[#13131333]`}>{props.subtitle}</span>
        </p>
        <div className={"w-[24px] h-[24px] flex items-center justify-center"}>
          <Image src={"/icons/expand_more_bottom.svg"}
                 alt={"expand_more_bottom"}
                 className={`transition-transform ${isExpanded ? "rotate-180" : ""}`}
                 width={8}
                 height={4} />
        </div>
      </div>
      <div
        ref={content}
        style={{ maxHeight: isExpanded ? `${content.current?.scrollHeight}px` : "0px" }}
        className={`transition-[max-height] duration-[0.6s] ${props.contentClassName || ""}`}
      >
        {props.children}
      </div>
    </div>
  );
}