import { useCallback, useMemo } from 'react';

import type { ItemLinksProps } 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 { useI18n } from '~/src/lib/i18n';
import { getCountryName } from '~/src/lib/utils/countriesByCode';
import wait from '~/src/lib/utils/wait';

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

  /**
   * Called when enter key pressed on <input>
   */
  onSubmit: () => void;
}

const INPUT_DEBOUNCE_MS = 400;

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

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

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

  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={useCallback(
            ({ value }) => {
              // REVIEW: this is causing a full page render on each keypress because it's
              // mutating the underlying `item` on the edit stage
              onTitleChange(value);
            },
            [onTitleChange]
          )}
        />
      </InputLabel>
      {activeTerritory && (
        <ConfirmButton
          height="4.6rem"
          margin={`${FORM_SECTION_SPACING} 0 0`}
          onClick={() => onTerritoryRemove(activeTerritory)}
          testId="removeTerritory"
          text={`Remove ${activeTerritoryName}`}
        />
      )}
      {withTerritoryOverridesInitial && (
        <Divider margin={`${FORM_SECTION_SPACING} 0`} isDashed />
      )}
      <SwitchSetting
        margin={`${FORM_SECTION_SPACING} 0 0`}
        title={t('itemEdit.labels.showMoreButton')}
        description={t('itemEdit.showMoreLinksHelp', {
          maxLinks: 7,
        })}
        testId="showMoreSwitch"
        value={!!withShowMore}
        onChange={useCallback(
          (value) => {
            updateLayoutSection({
              sectionPath,

              changedProps: {
                withShowMore: value,
              },
            });
          },
          [updateLayoutSection]
        )}
      />
      <SwitchSetting
        flexRow
        margin={`${FORM_SECTION_SPACING} 0 0`}
        title={t('itemEdit.labels.coloredIcons')}
        description={t('itemEdit.coloredIconsHelp')}
        value={!!withColoredIcons}
        testId="coloredIconsSwitch"
        onChange={useCallback(
          (value) => {
            updateLayoutSection({
              sectionPath,

              changedProps: {
                withColoredIcons: value,
              },
            });
          },
          [updateLayoutSection]
        )}
      />
      <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="Territory customizations"
        description="Customize the list of buttons based on the fan's country."
        testId="territoryOverridesSwitch"
        value={!!withTerritoryOverrides}
        onChange={onTerritoryOverridesChange}
      />
    </Form>
  );
};

export default ItemLinksSettings;
