import { animated, useSpring } from "@react-spring/web";
import WBRepeaterDeleteControl from "./WBRepeaterDeleteControl";
import WBRepeaterOrderControl from "./WBRepeaterOrderControls";

const useState = wp.element.useState;
const useEffect = wp.element.useEffect;
const useRef = wp.element.useRef;

const WBRepeaterRow = ({
  children,
  isAccordion,
  saveOpenState,
  isOpen = null,
  title,
  index,
  onChangeOrder,
  onDelete,
}) => {
  const [open, setOpen] = useState(isOpen === null ? true : isOpen);
  const [contentMaxHeight, setContentMaxHeight] = useState(0);
  const ref = useRef();

  useEffect(() => {
    const calcContentMaxHeight = () => {
      ref && ref.current && setContentMaxHeight(ref.current.scrollHeight);
    };

    calcContentMaxHeight();

    window.addEventListener("resize", () => calcContentMaxHeight());

    return () => window.removeEventListener("resize", calcContentMaxHeight());
  }, [ref, contentMaxHeight, children]);

  useEffect(() => {
    if (saveOpenState) {
      saveOpenState(open);
    }
  }, [open]);

  const { scY, y, ...props } = useSpring({
    scY: open ? -1 : 1,
    opacity: open ? 1 : 0,
    maxHeight: open ? `${contentMaxHeight}px` : "0px",
    config: { duration: 300 },
  });

  return (
    <div className="wb-input-repeater-row">
      <WBRepeaterOrderControl index={index} onChangeOrder={onChangeOrder} />
      {isAccordion && (
        <div style={{ width: "100%" }}>
          <div
            className="wb-input-repeater-accordion-title"
            onClick={() => setOpen(!open)}
          >
            <span className="wb-input-repeater-accordion-title-text">
              {title}
            </span>
            <div className="wb-input-repeater-accordion-expand">
              shrink / expand
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
                <path d="M344 0L488 0c13.3 0 24 10.7 24 24l0 144c0 9.7-5.8 18.5-14.8 22.2s-19.3 1.7-26.2-5.2l-39-39-87 87c-9.4 9.4-24.6 9.4-33.9 0l-32-32c-9.4-9.4-9.4-24.6 0-33.9l87-87L327 41c-6.9-6.9-8.9-17.2-5.2-26.2S334.3 0 344 0zM168 512L24 512c-13.3 0-24-10.7-24-24L0 344c0-9.7 5.8-18.5 14.8-22.2s19.3-1.7 26.2 5.2l39 39 87-87c9.4-9.4 24.6-9.4 33.9 0l32 32c9.4 9.4 9.4 24.6 0 33.9l-87 87 39 39c6.9 6.9 8.9 17.2 5.2 26.2s-12.5 14.8-22.2 14.8z" />
              </svg>
            </div>
          </div>
          <animated.div
            className="wb-input-repeater-fields"
            ref={ref}
            style={{ padding: 10, ...props }}
          >
            {children}
          </animated.div>
        </div>
      )}
      {!isAccordion && (
        <div className="wb-input-repeater-fields">{children}</div>
      )}
      <WBRepeaterDeleteControl index={index} onDelete={onDelete} />
    </div>
  );
};
export default WBRepeaterRow;
