import React, {useCallback, useMemo} from 'react';
import {Pressable, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {IconPhone, IconPhoneOff} from '@tabler/icons-react-native';
import {Typography, IconButton} from '@components';
import {useShowCallStatusBar} from '@modules/calls/store/selectors';
import {removeCallId, resetState} from '@modules/calls/store';
import {CallService} from '@modules/calls/utils';
import {navigate} from '@navigation/navigator';
import {useAppSelector} from '@redux/utils';
import {Screens} from '@shared/constants';
import {useTheme, ICON_SIZES} from '@shared/theme';

import {getWrapperStyle, styles} from './styles';

export function CallStatusBar() {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {top} = useSafeAreaInsets();
  const showCallStatusBar = useShowCallStatusBar();
  const callId = useAppSelector(({call}) => call.callId);

  const handlePress = useCallback(() => {
    navigate(Screens.CALLS_CALL, {callId, isCaller: false});
  }, [callId]);

  const handleEndCall = useCallback(() => {
    CallService.leaveCurrentCall();
    removeCallId();
    resetState();
  }, []);

  const wrapperStyle = useMemo(
    () => getWrapperStyle(top, theme.background.layout.brand),
    [theme.background.layout.brand, top],
  );

  if (!showCallStatusBar || !callId) {
    return null;
  }

  return (
    <View style={wrapperStyle}>
      <Pressable onPress={handlePress} style={styles.container}>
        <View
          style={[
            styles.phoneIconContainer,
            {backgroundColor: theme.background.elements.grey},
          ]}>
          <IconPhone size={ICON_SIZES.x5} color={theme.text.neutral.default} />
        </View>
        <View style={styles.textContainer}>
          <Typography variant="s" weight="semiBold">
            {t('calls.call_in_progress')}
          </Typography>
        </View>
        <IconButton
          Icon={IconPhoneOff}
          variant="error"
          iconColor={theme.text.neutral.inverted}
          onPress={handleEndCall}
          accessibilityLabel={t('calls.actions.hang_up')}
        />
      </Pressable>
    </View>
  );
}
