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

const INPUT_DEBOUNCE_MS = 400;

const VideosSettings = ({
  sectionPath,
  title,
  onSubmit,
  autoplay,
}: {
  sectionPath: string;
  title: string;
  onSubmit: () => void;
  autoplay?: boolean;
}) => {
  const { t } = useI18n();
  const { updateLayoutSection } = useEditActions();

  return (
    <Form
      onSubmit={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
          defaultValue={title}
          debounceTimeout={INPUT_DEBOUNCE_MS}
          onInputEnd={({ value }) => {
            updateLayoutSection({
              sectionPath,

              changedProps: {
                title: value,
              },
            });
          }}
        />
      </InputLabel>
      <SwitchSetting
        margin={`${FORM_SECTION_SPACING} 0 0`}
        testId="autoplaySwitch"
        title={t('itemEdit.videos.edit.autoplay')}
        description={t('itemEdit.videos.edit.autoplayDescription')}
        value={autoplay}
        onChange={(value) => {
          updateLayoutSection({
            sectionPath,
            changedProps: { autoplay: value },
          });
        }}
      />
    </Form>
  );
};

export default VideosSettings;
