import React, { useCallback, useEffect, useRef, useState } from "react";
import { ChevronUpIcon } from "@/assets/svgs";

const Collapser = ({ title = "Title", children }) => {
  const collapseRef = useRef(null);
  const [collapsed, setCollapsed] = useState(true);

  const toggleCollapse = useCallback(() => {
    if (collapseRef.current) {
      if (collapsed) {
        collapseRef.current.style.maxHeight = `${collapseRef?.current?.scrollHeight}px`;
        // collapseRef.current.style.overflowY = `auto`;
        setCollapsed(false);
      } else {
        collapseRef.current.style.maxHeight = null;
        // collapseRef.current.style.overflowY = "hidden";
        setCollapsed(true);
      }
    }
  }, [collapseRef, collapsed]);

  useEffect(() => {
    setTimeout(() => {
      // collapseRef.current.style.maxHeight = `100%`;
      collapseRef.current.style.maxHeight = `${collapseRef?.current?.scrollHeight}px`;
      // collapseRef.current.style.overflowY = `auto`;
      setCollapsed(false);
    }, 1000);
  }, []);

  return (
    <div className="w-full">
      {/*  */}
      <div className="my-2 flex w-full items-center justify-between self-stretch font-bold">
        <div className="grow font-['Inter'] text-sm font-bold capitalize leading-[1.0938rem] text-blue-950">
          {title}
        </div>
        <button className="h-fit w-fit ">
          <ChevronUpIcon
            onClick={toggleCollapse}
            className={`relative h-[1.125rem] w-[1.125rem] cursor-pointer ${
              collapsed ? "rotate-180" : ""
            }`}
          />
        </button>
      </div>
      {/*  */}
      <div
        ref={collapseRef}
        className="max-h-0 overflow-y-hidden transition-all"
      >
        {children}
      </div>
    </div>
  );
};

export default Collapser;
