import React, {useMemo} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {IconUsersGroup} from '@tabler/icons-react-native';
import {Typography, Avatar, Spinner} from '@components';
import {CallingState} from '@modules/calls/constants';
import {
  useCallingState,
  useCallMetadataParticipants,
  useGroupCall,
  useRemoteParticipants,
} from '@modules/calls/store/selectors';
import {useUserId} from '@redux/selectors';
import {useTheme} from '@shared/theme';

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

interface Props {
  onHangupCall: () => void;
  isCaller: boolean;
}

export function CallConnectingLayout({onHangupCall, isCaller}: Props) {
  const {t} = useTranslation();
  const {top, bottom} = useSafeAreaInsets();
  const {theme} = useTheme();

  const callingState = useCallingState();
  const remoteParticipants = useRemoteParticipants();
  const callParticipants = useCallMetadataParticipants();
  const userId = useUserId();
  const isCallReconnecting = callingState === CallingState.RECONNECTING;
  const isCallReconnectingFailed =
    callingState === CallingState.RECONNECTING_FAILED;
  const groupCall = useGroupCall();
  const containerStyle = useMemo(
    () => getContainerStyle(top, bottom),
    [top, bottom],
  );
  const isGroupCall = !!groupCall?.isGroupCall;
  const joinedCallee = remoteParticipants[0];
  const fallbackCallee =
    callParticipants.find(participant => participant.id !== userId) ??
    callParticipants[0];
  const fallbackCalleeName =
    fallbackCallee?.fullName || fallbackCallee?.name || undefined;
  const calleeName = isGroupCall
    ? groupCall?.callGroupName
    : fallbackCalleeName ?? joinedCallee?.name;
  const calleeAvatarUrl = isGroupCall
    ? undefined
    : joinedCallee?.profileImageURL ?? fallbackCallee?.profilePicture;

  return (
    <View style={containerStyle} testID="outgoing-call-layout">
      <View style={styles.participant}>
        {isCaller ? (
          <>
            {(calleeName || isGroupCall) && (
              <>
                <Avatar
                  size="lg"
                  name={!isGroupCall ? calleeName : undefined}
                  url={!isGroupCall ? calleeAvatarUrl ?? undefined : undefined}
                  Icon={isGroupCall ? IconUsersGroup : undefined}
                />
                {calleeName ? (
                  <Typography color={theme.white}>{calleeName}</Typography>
                ) : null}
              </>
            )}
            <Typography variant="xs" numberOfLines={1} color={theme.white}>
              {t('calls.calling')}
            </Typography>
          </>
        ) : (
          <Spinner />
        )}
        {(isCallReconnecting || isCallReconnectingFailed) && (
          <Typography color={theme.white}>
            {t('calls.reconnecting')}...
          </Typography>
        )}
      </View>
      <CallActionButtons onHangupCall={onHangupCall} />
    </View>
  );
}
