import type { FormListFieldData } from 'antd';
import { Form } from 'antd';
import { useMemo } from 'react';
import type { ChildrenType, LayoutType } from '.';
import { component } from './util';

interface FormListItemProps {
  children?: ChildrenType;
  value?: any;
  index: number;
  field: FormListFieldData;
  layout: LayoutType;
}

const FormListItem = (props: FormListItemProps) => {
  const { children, field, value, index, layout } = props;

  const eles = useMemo(() => {
    return Array.isArray(children)
      ? children.map((item) => component(item, value?.[index], index))
      : [component(children, value)];
  }, [children, index, value]);

  return (
    <>
      {eles.map((e) => {
        const { props: eleProps } = e || {};
        return (
          <Form.Item
            {...field}
            key={[field.name, eleProps?.name].join('-')}
            style={{ flex: 1 }}
            name={[field.name, eleProps?.name]}
            label={
              layout === 'vertical' ? (index === 0 ? eleProps?.label || ' ' : '') : eleProps?.label
            }
            rules={eleProps?.rules}
            hidden={eleProps?.hidden}
          >
            {e}
          </Form.Item>
        );
      })}
    </>
  );
};

export default FormListItem;
