import { useCallback, useMemo } from 'react';

import type { MerchSectionProps } 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 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<MerchSectionProps, 'items'> {
  sectionPath: string;
  onSubmit: () => void;
  activeTerritory?: string;
  withTerritoryOverrides: boolean;
  onTerritoryOverridesChange: (
    value: boolean,
    updateValue: (value: boolean) => void
  ) => void;
  onTitleChange: (title: string) => void;
  onTerritoryRemove: (territory: string) => void;
}

const INPUT_DEBOUNCE_MS = 400;

const MerchSettings = ({
  title,
  onTitleChange,
  onSubmit,
  withTerritoryOverrides,
  activeTerritory,
  onTerritoryOverridesChange,
  onTerritoryRemove,
}: SettingsContentProps) => {
  const { t } = useI18n();

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

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

  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') +
          (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
        flexRow
        margin={`${FORM_SECTION_SPACING} 0 0`}
        title="Territory customizations"
        description="Customize the list of merch based on the fan's country."
        testId="territoryOverridesSwitch"
        value={!!withTerritoryOverrides}
        onChange={onTerritoryOverridesChange}
      />
    </Form>
  );
};

export default MerchSettings;
