import React, {memo, useMemo, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {shallowEqual, useDispatch} from 'react-redux';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useUpdates} from 'expo-updates';
import {
  IconInfoCircle,
  IconLogout,
  IconSettings,
} from '@tabler/icons-react-native';
import {useNavigation} from '@react-navigation/native';
import {Badge, IconButton, Typography} from '@components';
import {useQuery} from '@hooks/queries-v5/useQuery';
import {showLogoutDialog} from '@modules/app/redux';
import {VERSION_CHECK_QUERY_KEYS} from '@modules/app/components/AppModals/components/UpdateReminderModal/constants';
import {useShowCallStatusBar} from '@modules/calls/store/selectors';
import {useAppSelector} from '@redux/utils';
import {getAppStoreVersion, getGooglePlayVersion} from '@services/versionCheck';
import {useTheme} from '@shared/theme';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';
import {
  checkAppVersionDifference,
  isIos,
  logAmplitudeEvent,
} from '@shared/utils';

import {getContainerStyle, styles} from './styles';
import {AppInformationModal} from './components/AppInformationModal';

const UPDATE_VERSION_THRESHOLD = 1;
const STALE_TIME_MS = 1000 * 60 * 60 * 2; // 2 hours

function ProfileNavbar() {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const {top} = useSafeAreaInsets();
  const showCallStatusBar = useShowCallStatusBar();
  const [showInfoModal, setShowInfoModal] = useState(false);
  const {isUpdatePending} = useUpdates();
  const {loading, changingCover, changingPhoto} = useAppSelector(
    ({profile}) => ({
      loading: profile.loading,
      changingCover: profile.changingCover,
      changingPhoto: profile.changingPhoto,
    }),
    shallowEqual,
  );

  const {data: storeVersion} = useQuery(
    VERSION_CHECK_QUERY_KEYS.store,
    isIos ? getAppStoreVersion : getGooglePlayVersion,
    {staleTime: STALE_TIME_MS},
  );

  const isReadyToInstall = useMemo(() => {
    if (!storeVersion || !storeVersion?.version) return false;
    return (
      !(
        checkAppVersionDifference(storeVersion.version) >=
        UPDATE_VERSION_THRESHOLD
      ) && isUpdatePending
    );
  }, [storeVersion, isUpdatePending]);

  const onPressLogout = () => dispatch(showLogoutDialog());

  const onPressInfo = () => {
    if (isUpdatePending) {
      logAmplitudeEvent(AMPLITUDE_EVENTS.GENERAL_EXPOUPDATE_AVAILABLE);
    }
    setShowInfoModal(true);
  };

  const onInfoModalClose = () => setShowInfoModal(false);

  const onPressSettings = () => navigation.navigate(Screens.SETTINGS);
  const containerStyle = useMemo(
    () =>
      getContainerStyle(
        showCallStatusBar,
        top,
        theme.background.layout.tertiary,
      ),
    [showCallStatusBar, theme.background.layout.tertiary, top],
  );

  return (
    <View style={styles.navbarLayer}>
      <View style={[styles.container, containerStyle]}>
        <View style={styles.navSection}>
          <View>
            <IconButton
              Icon={IconInfoCircle}
              onPress={onPressInfo}
              variant="tertiary"
            />
            {isReadyToInstall && <Badge show style={styles.badge} />}
          </View>
        </View>
        <View style={styles.navSection}>
          <Typography weight="semiBold" align="center" numberOfLines={1}>
            {t('profile.my_profile')}
          </Typography>
        </View>
        <View style={[styles.rightContainer, styles.navSection]}>
          <IconButton
            Icon={IconSettings}
            onPress={onPressSettings}
            variant="tertiary"
          />
          <IconButton
            Icon={IconLogout}
            onPress={onPressLogout}
            variant="tertiary"
            testID="logout-header-button"
            accessibilityLabel={t('authentication.logout')}
            disabled={loading || changingCover || changingPhoto}
            style={styles.logoutContainer}
          />
        </View>
      </View>
      <AppInformationModal
        show={showInfoModal}
        onClose={onInfoModalClose}
        isReadyToInstall={isReadyToInstall}
      />
    </View>
  );
}

export default memo(ProfileNavbar);
