import { useCallback, useMemo } from 'react';

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

import { ConfirmButton } from '~/src/components/Button/ConfirmButton';
import Divider from '~/src/components/Divider';
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 useIsEnabled from '~/src/hooks/useIsEnabled';
import { useI18n } from '~/src/lib/i18n';
import { getCountryName } from '~/src/lib/utils/countriesByCode';
import wait from '~/src/lib/utils/wait';
import { Features } from '~/src/store/session/types';

interface SettingsContentProps
  extends Omit<
    PresaveButtonsProps,
    'items' | 'layoutData' | 'testId' | 'territoryOverrides'
  > {
  sectionPath: string;
  activeTerritory?: string;
  withTerritoryOverrides: boolean;
  onTitleChange: (title: string) => void;
  onTerritoryRemove: (territory: string) => void;
  onTerritoryOverridesChange: (value: boolean) => void;
  onSubmit: () => void;
}

const INPUT_DEBOUNCE_MS = 400;

const SubscribeButtonsSettings = ({
  sectionPath,
  withColoredIcons,
  withAlphabeticalSort,
  activeTerritory,
  title,
  withTerritoryOverrides,
  withEmailAndOptInsBeforePresave,
  onTerritoryOverridesChange,
  onTerritoryRemove,
  onTitleChange,
  onSubmit,
}: SettingsContentProps) => {
  const { updateLayoutSection } = useEditActions();
  const { t } = useI18n();

  const isEmailCollectionEnabled = useIsEnabled(
    Features.PRESAVE_EMAIL_COLLECTION
  );

  const withTerritoryOverridesInitial = useMemo(
    () => withTerritoryOverrides,
    []
  );

  const activeTerritoryName = withTerritoryOverridesInitial
    ? activeTerritory
      ? getCountryName(activeTerritory)
      : 'Default'
    : undefined;

  return (
    <Form
      onSubmit={useCallback(async () => {
        await wait(INPUT_DEBOUNCE_MS);
        onSubmit();
      }, [onSubmit])}
    >
      <InputLabel
        value={
          t('itemEdit.labels.componentTitle') +
          (activeTerritoryName ? ` · ${activeTerritoryName}` : '')
        }
      >
        <TextInput
          defaultValue={title}
          testId="titleInput"
          debounceTimeout={INPUT_DEBOUNCE_MS}
          onInputEnd={({ value }) => {
            onTitleChange(value);
          }}
        />
      </InputLabel>
      {activeTerritory && (
        <ConfirmButton
          height="4.5rem"
          margin={`${FORM_SECTION_SPACING} 0 0`}
          onClick={() => onTerritoryRemove(activeTerritory)}
          testId="removeTerritory"
          text={t('itemEdit.actions.removeTerritory', {
            territory: activeTerritoryName!,
          })}
        />
      )}
      {withTerritoryOverridesInitial && (
        <Divider margin={`${FORM_SECTION_SPACING} 0`} isDashed />
      )}
      <SwitchSetting
        margin={`${FORM_SECTION_SPACING} 0 0`}
        title={t('itemEdit.labels.coloredIcons')}
        description={t('itemEdit.coloredIconsHelp')}
        value={!!withColoredIcons}
        onChange={(value) => {
          updateLayoutSection({
            sectionPath,

            changedProps: {
              withColoredIcons: value,
            },
          });
        }}
      />
      <SwitchSetting
        testId="alphabeticalSortSwitch"
        margin={`${FORM_SECTION_SPACING} 0 0`}
        title={t('itemEdit.labels.alphabeticalSort')}
        description={t('itemEdit.alphabeticalSortHelp')}
        value={withAlphabeticalSort}
        onChange={useCallback(
          (value) => {
            updateLayoutSection({
              sectionPath,

              changedProps: {
                withAlphabeticalSort: value,
              },
            });
          },
          [updateLayoutSection]
        )}
      />
      <SwitchSetting
        flexRow
        margin={`${FORM_SECTION_SPACING} 0 0`}
        title={t('itemEdit.labels.territoryOverrides')}
        description={t('itemEdit.territoryOverridesHelp')}
        testId="territoryOverridesSwitch"
        value={!!withTerritoryOverrides}
        onChange={onTerritoryOverridesChange}
      />
      {isEmailCollectionEnabled && (
        <SwitchSetting
          flexRow
          margin={`${FORM_SECTION_SPACING} 0 0`}
          title={t('itemEdit.labels.emailAndOptInsBeforePresave')}
          description={t('itemEdit.emailAndOptInsBeforePresaveHelp')}
          testId="emailAndOptInsBeforePresaveSwitch"
          value={!!withEmailAndOptInsBeforePresave}
          onChange={(value) => {
            updateLayoutSection({
              sectionPath,

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

export default SubscribeButtonsSettings;
