import {useCallback} from 'react';
import {Keyboard, ListRenderItem, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import * as Flags3x2 from 'country-flag-icons/string/3x2';
import * as Flags1x1 from 'country-flag-icons/string/1x1';
import {SvgXml} from 'react-native-svg';
import {IconChevronDown} from '@tabler/icons-react-native';
import {Menu} from '@components/_HuGo/Menu';
import {ListRow} from '@components/_HuGo/List/';
import {Typography} from '@components/_core/Typography';
import {useModalHandler} from '@hooks/useModalHandler';
import {COUNTRIES, ICountry} from '@shared/countries';
import {useTheme} from '@shared/theme';

import {InputCommonProps} from '../../../../interfaces';
import {InputBox} from '../../../InputBox';
import {styles} from './style';

export type FlagKey = keyof typeof Flags3x2;

interface CountryCodeSelectorProps extends InputCommonProps {
  countryCode: FlagKey;
  setCountry: (country: ICountry) => void;
}

const DEFAULT_SNAP_POINTS = ['50%', '100%'];

export function CountryCodeSelector({
  countryCode,
  setCountry,
  isSuccess,
  isError,
  disabled,
  size,
}: CountryCodeSelectorProps) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {isVisible, onOpenModal, onCloseModal} = useModalHandler();

  const onItemPress = useCallback(
    (item: ICountry) => () => {
      onCloseModal();
      setCountry(item);
    },
    [onCloseModal, setCountry],
  );

  const renderItem: ListRenderItem<ICountry> = useCallback(
    ({item}) => (
      <ListRow onPress={onItemPress(item)} style={styles.menuItem}>
        <View style={styles.circleFlag}>
          {item.code in Flags1x1 && (
            <SvgXml xml={Flags1x1[item.code as FlagKey]} />
          )}
        </View>
        <ListRow.Title
          title={t(
            `backoffice_only.form_country_code.${item.code.toLowerCase()}`,
          )}
        />
        <Typography>{item.dialCode}</Typography>
      </ListRow>
    ),
    [onItemPress, t],
  );

  const filterRule = useCallback(
    (item: ICountry, searchText: string) => {
      return t(`backoffice_only.form_country_code.${item.code.toLowerCase()}`)
        .toLowerCase()
        .includes(searchText.toLowerCase());
    },
    [t],
  );

  const onPressSelector = useCallback(() => {
    Keyboard.dismiss();
    onOpenModal();
  }, [onOpenModal]);

  return (
    <>
      <InputBox
        isSuccess={isSuccess}
        isError={isError}
        focused={isVisible}
        disabled={disabled}
        onPress={onPressSelector}
        style={styles.boxContainer}
        size={size}
        showStateIcon={false}
        RightComponent={
          <IconChevronDown
            color={theme.text.neutral[disabled ? 'disabled' : 'default']}
            testID="country-code-selector-icon"
          />
        }>
        {!!countryCode && countryCode in Flags3x2 && (
          <SvgXml xml={Flags3x2[countryCode]} style={styles.rectangleFlag} />
        )}
      </InputBox>
      <Menu
        enableDynamicSizing={false}
        snapPoints={DEFAULT_SNAP_POINTS}
        title={t('service_management.phone')}
        searchPlaceholder={t('general.search')}
        data={COUNTRIES}
        renderItem={renderItem}
        isVisible={isVisible}
        onClose={onCloseModal}
        filterable
        filterRule={filterRule}
        useBottomSheetTextInput
        contentContainerStyle={styles.menuContainer}
      />
    </>
  );
}
