import React, { CSSProperties, ReactNode } from "react";
import { View } from "@tarojs/components";
import { Direction } from "@/components/global/direction";
import styles from "./oui-spacer.module.scss";

interface OuiSpacerProps {
  direction?: Direction;
  gap?: number;
  children?: ReactNode;
  justifyContent?: string;
  alignItems?:
    | "flex-start"
    | "center"
    | "flex-end"
    | "baseline"
    | "start"
    | "end";
  style?: CSSProperties;
}

function OuiSpacer({
  direction = Direction.vertical,
  gap = 8,
  justifyContent,
  alignItems,
  style,
  children,
}: OuiSpacerProps) {
  const generateComponentStyle = (): CSSProperties | undefined => {
    if (direction === Direction.horizontal) {
      return {
        flexDirection: "row",
        justifyContent,
        alignItems,
      };
    }
    if (direction === Direction.vertical) {
      return {
        flexDirection: "column",
        justifyContent,
        alignItems,
      };
    }
  };

  const generateChildMargin = (): string | undefined => {
    if (direction === Direction.vertical) {
      return `${gap}px 0 0 0`;
    }
    if (direction === Direction.horizontal) {
      return `0 0 0 ${gap}px`;
    }
  };

  const generateChildStyle = (index: number): CSSProperties | undefined => {
    if (index !== 0) {
      return {
        margin: generateChildMargin(),
      };
    }
  };
  return (
    <View
      className={styles.component}
      style={{ ...generateComponentStyle(), ...style }}
    >
      {React.Children.toArray(children).map(
        (
          item: React.ReactElement<
            any,
            string | React.JSXElementConstructor<any>
          >,
          index: number
        ) => {
          return React.cloneElement(item, {
            ...item.props,
            style: {
              ...(item.props.style || {}),
              ...generateChildStyle(index),
            },
          });
        }
      )}
    </View>
  );
}

export default OuiSpacer;
