import React, { Children, useMemo } from "react";

import { View, ViewProps } from "../View";

type Props = {
  GapComponent?: React.ComponentType<any>;
  align?: "flex-start" | "flex-end" | "center" | "baseline" | "stretch";
  gap?: number;
  inline?: boolean;
  justify?:
    | "flex-start"
    | "flex-end"
    | "center"
    | "space-between"
    | "space-around"
    | "space-evenly";
  reverse?: boolean;
} & ViewProps;

const Stack = ({
  GapComponent = View,
  align = "stretch",
  children,
  gap = 0,
  inline = false,
  justify = "flex-start",
  reverse = false,
  style = null,
  ...viewProps
}: Props) => {
  const viewStyle = useMemo(
    () => [
      {
        alignItems: align,
        flexDirection: inline
          ? reverse
            ? "row-reverse"
            : "row"
          : reverse
          ? "column-reverse"
          : "column",
        justifyContent: justify,
      },
      ...[].concat(style),
    ],
    [align, inline, reverse, justify, style]
  );

  const gapStyle = useMemo(() => (inline ? { width: gap } : { height: gap }), [
    inline,
    gap,
  ]);

  return (
    <View style={viewStyle} {...viewProps}>
      {Children.toArray(children)
        .filter(Boolean)
        .map((child, index) => (
          <React.Fragment key={`stack-${index}`}>
            {index !== 0 && <GapComponent style={gapStyle} />}
            {child}
          </React.Fragment>
        ))}
    </View>
  );
};

export default Stack;
