/* eslint-disable react-hooks/exhaustive-deps */
import React, {useRef, useEffect, useState} from 'react';
import {View, Text, Image, TouchableOpacity} from 'react-native';
import Modal from 'react-native-modal';
import {Icon} from 'components';
import {Colors} from 'global-styles';
import {useTranslation} from 'react-i18next';
import styles from './styles';

const LANGUAGES = [
  {
    code: 'id',
    label: 'Bahasa Indonesia',
    icon: require('assets/images/indonesia-flag.png'),
  },
  {
    code: 'en',
    label: 'English',
    icon: require('assets/images/english-flag.png'),
  },
];

const ModalLanguage = props => {
  const {t, i18n} = useTranslation();
  const {isVisible, onSave, onClose} = props;
  const [selected, setSelected] = useState(i18n.language);

  const setLanguage = language => {
    setSelected(language.code);
  };

  const saveLanguage = () => {
    onSave(selected);
    return i18n.changeLanguage(selected);
  };

  const closeModal = () => {
    setSelected(i18n.language);
    onClose();
  };

  return (
    <Modal isVisible={isVisible} style={styles.modal}>
      <View style={styles.container}>
        <TouchableOpacity
          onPress={() => closeModal()}
          style={styles.buttonClose}>
          <Icon name="close" type="AntDesign" style={styles.buttonCloseIcon} />
        </TouchableOpacity>
        <View style={styles.content}>
          <Text style={styles.title}>{t('select_language')}</Text>
          <View style={styles.languageSection}>
            {LANGUAGES.map((item, index) => (
              <TouchableOpacity
                onPress={() => setLanguage(item)}
                key={index}
                style={styles.languageItem}>
                <View style={styles.languageInfo}>
                  <Image source={item.icon} style={styles.languageFlag} />
                  <Text style={styles.languageName}>{item.label}</Text>
                </View>
                <View style={styles.selected(selected === item.code)}>
                  {selected === item.code && (
                    <View style={styles.selectedItem} />
                  )}
                </View>
              </TouchableOpacity>
            ))}
          </View>
          <TouchableOpacity
            onPress={() => saveLanguage()}
            style={styles.button}>
            <Text style={styles.buttonTitle}>{t('save')}</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Modal>
  );
};

export default ModalLanguage;
