import * as React from "react";
import { get } from "lodash";
import { PropertiesProps } from "../types";

import PropertiesBuilder from "@sc/modules/v2/Properties/components/generator";
import { updateSection } from "@sc/modules/v2/Properties/components/generator";

import bulletBuilderSettings from "../settings";

import { ListBuilder } from "./ListBuilder";
import { SectionTypes } from "@sc/modules/v2/Properties/types";
import { IconTypes } from "../../Icon";

/**
 * The property window that shows for the FormBuilderEditorObject
 */
const BulletBuilderPropertyWindow: React.FC<PropertiesProps> = (props) => {
  const [settings, setSettings] = React.useState(props.settings);

  const handleSettingsChange = (id, settings, dbUpdate = true) => {
    const { updateComponentSettings } = props;
    setSettings(settings);
    if (dbUpdate) updateComponentSettings(id, settings, true, false);
  };

  const { properties } = bulletBuilderSettings;
  const { sections } = properties.main;

  const withListBuilder = updateSection(sections, "BulletBuilderSettings", {
    component: (
      <ListBuilder
        {...settings}
        onChange={(data) =>
          handleSettingsChange(settings.id, { ...props.settings, data })
        }
      />
    ),
  });

  const withIconSelector = updateSection(
    withListBuilder,
    SectionTypes.ICONSELECTOR,
    {
      onChange: (e) =>
        handleSettingsChange(settings.id, { ...settings, icon: IconTypes[e] }),
    }
  );

  const updatedProperties = {
    ...properties,
    main: { ...properties.main, sections: withIconSelector },
  };

  return <PropertiesBuilder data={updatedProperties} {...props} />;
};

export default React.memo(BulletBuilderPropertyWindow);
