import { useCallback } from 'react';

import type { IconLinksSectionProps } from '../types';

import Form from '~/src/components/Form';
import InputLabel from '~/src/components/InputLabel';
import { useEditActions } from '~/src/components/ItemPage/ItemPageEdit/useEditActions';
import TextInput from '~/src/components/TextInput';
import { useI18n } from '~/src/lib/i18n';
import wait from '~/src/lib/utils/wait';

interface SettingsContentProps
  extends Omit<
    IconLinksSectionProps,
    'links' | 'layoutData' | 'style' | 'testId'
  > {
  sectionPath: string;
  onSubmit: () => void;
  isShared: boolean | undefined;
}

const INPUT_DEBOUNCE_MS = 400;

const IconLinksSettings = ({
  sectionPath,
  title,
  isShared,
  onSubmit,
}: SettingsContentProps) => {
  const { t } = useI18n();
  const { updateLayoutSection } = useEditActions();

  return (
    <Form
      onSubmit={useCallback(async () => {
        // don't call submit until we know the layout has been updated after debounce
        await wait(INPUT_DEBOUNCE_MS);

        onSubmit();
      }, [])}
    >
      <InputLabel value={t('itemEdit.labels.componentTitle')}>
        <TextInput
          isDisabled={isShared}
          defaultValue={title}
          testId="sectionTitleInput"
          debounceTimeout={INPUT_DEBOUNCE_MS}
          onInputEnd={({ value }) => {
            updateLayoutSection({
              sectionPath,

              changedProps: {
                title: value,
              },
            });
          }}
        />
      </InputLabel>
    </Form>
  );
};

export default IconLinksSettings;
