import { createDynamicField } from '@/modules/forms/helpers/createDynamicField';

const parseMetadataToState = (metadata, isDuplicate) => {
  const { globalConfig, widget } = JSON.parse(metadata);
  const staticWidgets = widget.props[0].widget.props;
  const formWidget = widget.props[1].widget.props;

  const { fields, submitButton: submitButtonProps, skipButton: skipButtonProps } = formWidget;

  const dynamicFields = fields.map((field) => {
    const {
      widget: { component, props },
    } = field;
    const createdField = createDynamicField(component, {
      ...props,
      isTypeDisabled: !isDuplicate,
    });

    return createdField;
  });

  const description = staticWidgets.find((item) => item.widget.component === 'Description')?.widget?.props?.text ?? '';

  const privacyPolicy = {
    title: globalConfig.links.privacy.title,
    src: globalConfig.links.privacy.src,
  };

  const termsConditions = {
    isActive: !globalConfig.links.termsConditions.isHidden,
    title: globalConfig.links.termsConditions.title,
    src: globalConfig.links.termsConditions.src,
  };

  const submitButton = {
    title: submitButtonProps.title,
  };

  const skipButton = {
    isActive: !skipButtonProps.isHidden,
    title: skipButtonProps.title,
  };

  const style = {
    bgColor: globalConfig.styles.bgColor,
    alignItems: globalConfig.styles.alignment,
    fontFamily: globalConfig.styles.font.family,
    fontSize: globalConfig.styles.font.size,
    fontColor: globalConfig.styles.font.color,
    submitButtonBgColor: submitButtonProps.bgColor,
    submitButtonFontColor: submitButtonProps.textColor,
  };

  return {
    description,
    privacyPolicy,
    termsConditions,
    submitButton,
    skipButton,
    style,
    dynamicFields,
  };
};

export default parseMetadataToState;
