import React, {memo, useCallback} from 'react';
import {Pressable} from 'react-native';
import {useTranslation} from 'react-i18next';
import {COUNTRIES, ICountry} from '@shared/countries';
import {COLORS} from '@shared/colors';
import PickerItem from '@components/PhoneInput/components/PickerItem';
import {BottomModalList} from '@components/Modals';

import {styles} from './styles';

interface Props {
  isVisible: boolean;
  onClose: () => void;
  onSelect: (value: ICountry) => void;
  countrySelected?: ICountry;
  showDialCode?: boolean;
}

function CountriesModal({
  isVisible,
  onClose,
  onSelect,
  countrySelected,
  showDialCode = true,
}: Props) {
  const {t} = useTranslation();

  const renderItem = useCallback(
    ({item}: {item: ICountry}) => {
      const selected = countrySelected?.code === item.code;
      return (
        <Pressable onPress={() => onSelect(item)} style={styles.countryRow}>
          <PickerItem
            label={`${item.flag} ${item.name} ${
              showDialCode ? item.dialCode : ''
            }`}
            color={selected ? COLORS.PRIMARY : COLORS.DISALBED_LIGHT}
            textColor={selected ? COLORS.WHITE : COLORS.BLACK}
          />
        </Pressable>
      );
    },
    [countrySelected, onSelect, showDialCode],
  );

  const keyExtractor = useCallback(
    (item: ICountry) => `${item.code}-${item.dialCode}`,
    [],
  );

  const filterRule = useCallback(
    (item: ICountry, searchText: string) =>
      item.name.toLowerCase().includes(searchText),
    [],
  );

  return (
    <BottomModalList
      title={t(
        showDialCode ? 'general.select_country_code' : 'general.select_country',
      )}
      data={COUNTRIES}
      renderItem={renderItem}
      keyExtractor={keyExtractor}
      isVisible={isVisible}
      onClose={onClose}
      filterable
      filterRule={filterRule}
    />
  );
}

export default memo(CountriesModal);
