import React from 'react';
import { View, Text, TouchableOpacity, Linking } 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 { useMessagesStore } from 'src/stores/unreadMessagesStore';
import { useFriendsNotificationsStore } from 'src/stores/friendsNotificationsStore';
import { clearLocalDatabaseOnLogout } from 'src/watermelondb/features/chat/data/chat.repo';
import { stopAutoSyncListener } from 'src/watermelondb/features/chat/networkSync';

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

  const handleClose = async () => {
    if (navigateToLogin) {
      stopAutoSyncListener();
      await clearLocalDatabaseOnLogout();

      storage.remove('token');
      storage.remove('uid');
      storage.remove('currentUserData');
      storage.remove('showNomads');
      storage.remove('filterSettings');
      storage.remove('visitedRegions');
      storage.remove('visitedCountries');
      storage.remove('visitedDares');
      storage.remove('visitedSeries');

      updateNotificationStatus();
      updateUnreadMessagesCount();

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

  const handleGoToWeb = () => {
    Linking.openURL('https://nomadmania.com/blog-authentication/').catch((err) =>
      console.error('Failed to open auth URL:', err)
    );
    hideError();
  };

  return (
    <Modal isVisible={!!error} onModalHide={resetErrorState}>
      <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}>
              {premiumError
                ? 'This feature is available to Premium users. Premium account settings can be managed on our website.'
                : `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={navigateToAuth ? handleGoToWeb : handleClose}
                children="OK"
              />
            </View>
          </View>
        </View>
      </View>
    </Modal>
  );
};
