import React, { useState } from 'react';
import { View, Image, Linking, Text } from 'react-native';
import { CommonActions, useNavigation } from '@react-navigation/native';

import { WarningModal } from '../WarningModal';
import { MenuButton } from '../MenuButton';
import { styles } from './styles';
import { StoreType, storage } from 'src/storage';
import { useDeleteUserMutation } from '@api/app';
import { Colors } from 'src/theme';
import { NAVIGATION_PAGES } from 'src/types';

import MailIcon from '../../../assets/icons/mail.svg';
import DocumentIcon from '../../../assets/icons/document.svg';
import ExitIcon from '../../../assets/icons/exit.svg';
import UserXMark from '../../../assets/icons/user-xmark.svg';
import InfoIcon from 'assets/icons/info-solid.svg';
import BellIcon from 'assets/icons/notifications/bell-solid.svg';
import SharingIcon from 'assets/icons/location-sharing.svg';
import BagIcon from 'assets/icons/bag.svg';

import { APP_VERSION } from 'src/constants';
import { useNotification } from 'src/contexts/NotificationContext';
import { useMessagesStore } from 'src/stores/unreadMessagesStore';
import { SafeAreaView } from 'react-native-safe-area-context';
import { usePostIsFeatureActiveQuery } from '@api/location';

export const MenuDrawer = (props: any) => {
  const { mutate: deleteUser } = useDeleteUserMutation();
  const token = storage.get('token', StoreType.STRING) as string;
  const { data: isFeatureActive } = usePostIsFeatureActiveQuery(token, !!token);
  const navigation = useNavigation();
  const [modalInfo, setModalInfo] = useState({
    visible: false,
    type: 'confirm',
    message: '',
    action: () => {}
  });
  const { updateNotificationStatus } = useNotification();
  const updateUnreadMessagesCount = useMessagesStore((state) => state.updateUnreadMessagesCount);

  const openModal = (type: string, message: string, action: any) => {
    setModalInfo({
      visible: true,
      type,
      message,
      action
    });
  };

  const closeModal = () => {
    setModalInfo({ ...modalInfo, visible: false });
  };

  const handleLogout = () => {
    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 }]
      })
    );
  };

  const handleDeleteAccount = () => {
    deleteUser({ token }, { onSuccess: handleLogout });
  };

  return (
    <>
      <SafeAreaView style={styles.container}>
        <View style={{ flex: 1 }}>
          <View style={styles.logoContainer}>
            <Image source={require('../../../assets/logo-ua.png')} style={styles.logo} />
          </View>
          <MenuButton
            label="Info"
            icon={<InfoIcon fill={Colors.DARK_BLUE} width={20} height={20} />}
            red={false}
            buttonFn={() => navigation.navigate(NAVIGATION_PAGES.INFO as never)}
          />
          <MenuButton
            label="Contact Us"
            icon={<MailIcon fill={Colors.DARK_BLUE} width={20} height={20} />}
            red={false}
            buttonFn={() => Linking.openURL('https://nomadmania.com/contact/')}
          />
          <MenuButton
            label="Terms & Conditions"
            icon={<DocumentIcon fill={Colors.DARK_BLUE} width={20} height={20} />}
            red={false}
            buttonFn={() => Linking.openURL('https://nomadmania.com/terms/')}
          />
          {token && (
            <MenuButton
              label="Notifications"
              icon={<BellIcon fill={Colors.DARK_BLUE} width={20} height={20} />}
              red={false}
              buttonFn={() =>
                // todo: add types
                // @ts-ignore
                navigation.navigate(NAVIGATION_PAGES.MENU_DRAWER, {
                  screen: NAVIGATION_PAGES.NOTIFICATIONS
                })
              }
            />
          )}
          {isFeatureActive && isFeatureActive.active && (
            <MenuButton
              label="Location sharing"
              icon={<SharingIcon fill={Colors.DARK_BLUE} width={20} height={20} />}
              red={false}
              buttonFn={() =>
                // @ts-ignore
                navigation.navigate(NAVIGATION_PAGES.MENU_DRAWER, {
                  screen: NAVIGATION_PAGES.LOCATION_SHARING
                })
              }
            />
          )}
          <MenuButton
            label="Shop"
            icon={<BagIcon fill={Colors.DARK_BLUE} width={20} height={20} />}
            red={false}
            buttonFn={() => Linking.openURL('https://nomadmania.com/product-category/merchandise/')}
          />
        </View>

        <View style={styles.bottomMenu}>
          {token ? (
            <>
              <MenuButton
                label="Logout"
                icon={<ExitIcon fill={Colors.RED} width={20} height={20} />}
                red={true}
                buttonFn={() =>
                  openModal('confirm', 'Are you sure you want to logout?', handleLogout)
                }
              />
              <MenuButton
                label="Delete account"
                icon={<UserXMark fill={Colors.RED} width={20} height={20} />}
                red={true}
                buttonFn={() =>
                  openModal(
                    'confirm',
                    'Are you sure you want to delete your account?',
                    handleDeleteAccount
                  )
                }
              />
            </>
          ) : null}

          <View style={{ gap: 6, marginTop: 16 }}>
            <Text style={styles.bottomText}>Version {APP_VERSION}</Text>
            {/* <Text style={styles.bottomText}>
              Map server:{'\n'}
              {FASTEST_MAP_HOST}
            </Text> */}
          </View>
        </View>
      </SafeAreaView>

      <WarningModal
        isVisible={modalInfo.visible}
        onClose={closeModal}
        type={modalInfo.type}
        message={modalInfo.message}
        action={() => {
          modalInfo.action();
          closeModal();
        }}
      />
    </>
  );
};
