import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import Modal from 'react-native-modal';
import { useError } from 'src/contexts/ErrorContext';

import { styles } from '../WarningModal/styles';
import { Colors } from 'src/theme';

import CloseIcon from 'assets/icons/close.svg';
import { ButtonVariants } from 'src/types/components';
import { Button } from '../Button';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import { storage } from 'src/storage';
import { useNotification } from 'src/contexts/NotificationContext';
import { useMessagesStore } from 'src/stores/unreadMessagesStore';

export const ErrorModal = () => {
  const { error, hideError, navigateToLogin } = useError();
  const navigation = useNavigation();
  const { updateNotificationStatus } = useNotification();
  const updateUnreadMessagesCount = useMessagesStore((state) => state.updateUnreadMessagesCount);


  const handleClose = () => {
    if (navigateToLogin) {
      storage.remove('token');
      storage.remove('uid');
      storage.remove('currentUserData');
      storage.remove('showNomads');
      storage.remove('filterSettings');
      updateNotificationStatus();
      updateUnreadMessagesCount();

      navigation.dispatch(
        CommonActions.reset({
          index: 1,
          routes: [{ name: NAVIGATION_PAGES.WELCOME }]
        })
      );
    }
    hideError();
  };

  return (
    <Modal isVisible={!!error}>
      <View style={styles.centeredView}>
        <View style={styles.modalView}>
          <View style={{ alignSelf: 'flex-end' }}>
            <TouchableOpacity onPress={handleClose}>
              <CloseIcon fill={Colors.LIGHT_GRAY} />
            </TouchableOpacity>
          </View>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>Oops!</Text>
            <Text style={styles.modalText}>An error occurred: {error}</Text>
            <View style={styles.buttonContainer}>
              <Button
                variant={ButtonVariants.OPACITY}
                containerStyles={{
                  borderColor: Colors.DARK_BLUE,
                  backgroundColor: Colors.DARK_BLUE,
                  width: '60%'
                }}
                textStyles={{
                  color: Colors.WHITE
                }}
                onPress={handleClose}
                children="OK"
              />
            </View>
          </View>
        </View>
      </View>
    </Modal>
  );
};
