import React, { CSSProperties, ReactElement, ReactNode } from "react";
import { View } from "@tarojs/components";
import styles from "./oui-form.module.scss";
import OuiTip from "@/components/oui-tip/oui-tip";
import OuiFormItem from "./oui-form-item/oui-form-item";
import OuiLine from "@/components/oui-line/oui-line";

class OuiFormProps {
  type?: "card" | "cover";
  align?: "left" | "center" | "right" | "begin" | "end";
  style?: CSSProperties;
  margin?: number;
  radius?: number;
  color?: string;
  labelWidth?: string;
  children: ReactNode;
}
function OuiForm({
  type = "card",
  align = "begin",
  style,
  margin = 16,
  radius = 16,
  color = "#ffffff",
  labelWidth = "5em",
  children,
}: OuiFormProps) {
  const generateComponentStyle = (): CSSProperties | undefined => {
    if (type === "card") {
      return {
        margin: `${margin}px`,
        borderRadius: `${radius}px`,
        backgroundColor: color,
      };
    }
    if (type === "cover") {
      return {
        backgroundColor: color,
      };
    }
  };

  const generateChildren = (): ReactNode | undefined => {
    const elements = React.Children.toArray(children);
    return elements.map((item: ReactElement, index: number) => {
      if (item.type !== OuiFormItem) {
        return (
          <OuiTip theme="danger">
            children of oui-form just want oui-form-item
          </OuiTip>
        );
      }
      return [
        index > 0 && index < elements.length ? <OuiLine /> : null,
        React.cloneElement(
          item,
          {
            labelWidth: labelWidth,
            align: align,
            ...item.props,
          },
          item.props["children"]
        ),
      ]
        .filter((item) => item != null)
        .flat();
    });
  };

  return (
    <View
      className={styles.component}
      style={{ ...generateComponentStyle(), ...style }}
    >
      {generateChildren()}
    </View>
  );
}

export default OuiForm;
