import {memo, useCallback, useState} from 'react';
import {StyleSheet, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconPhone, IconVideo} from '@tabler/icons-react-native';
import {useCallInChannel} from '@modules/chats/hooks';
import {useStartCall} from '@modules/calls/hooks';
import {
  CallStartButton,
  DialogMissingCallPermission,
  CallJoinButton,
} from '@modules/calls/components';
import {useHasActiveCall} from '@modules/calls/store/selectors';
import {useShallowConversation} from '@modules/chats/store';

function CallButtonsComponent({channel}: {channel: string}) {
  const {t} = useTranslation();
  const [showMissingCallPermissions, setShowMissingCallPermissions] =
    useState(false);
  const [pressedButton, setPressedButton] = useState<'video' | 'audio' | null>(
    null,
  );
  const conversation = useShallowConversation(channel, state => ({
    is_channel: !!state.is_channel,
    name: state.name,
  }));
  const hasActiveCall = useHasActiveCall();

  const {callId, externalCallId, isOngoingCall, isCallEnabled} =
    useCallInChannel(channel);

  const onRefusePermissions = useCallback(() => {
    setShowMissingCallPermissions(true);
  }, []);

  const {startVideoCall, startAudioCall, isCreatingCall} = useStartCall({
    channel,
    isGroup: !!conversation?.is_channel,
    groupName: conversation?.name,
    onRefusePermissions,
  });

  const closeDialog = useCallback(() => {
    setShowMissingCallPermissions(false);
  }, []);

  const onVideoStartCall = useCallback(() => {
    setPressedButton('video');
    startVideoCall();
  }, [startVideoCall]);

  const onAudioStartCall = useCallback(() => {
    setPressedButton('audio');
    startAudioCall();
  }, [startAudioCall]);

  if (!isCallEnabled || (isOngoingCall && !callId)) {
    return null;
  }

  if (isOngoingCall && hasActiveCall) {
    return null;
  }

  return isOngoingCall ? (
    <CallJoinButton callId={callId!} externalCallId={externalCallId} />
  ) : (
    <>
      <View style={styles.container} accessible={false}>
        <CallStartButton
          onPress={onVideoStartCall}
          isLoading={isCreatingCall && pressedButton === 'video'}
          disabled={hasActiveCall}
          icon={IconVideo}
          accessibilityLabel={t('calls.video_call')}
        />
        <CallStartButton
          onPress={onAudioStartCall}
          isLoading={isCreatingCall && pressedButton === 'audio'}
          disabled={hasActiveCall}
          icon={IconPhone}
          accessibilityLabel={t('calls.audio_call')}
        />
      </View>
      <DialogMissingCallPermission
        isVisible={showMissingCallPermissions}
        onClose={closeDialog}
      />
    </>
  );
}

export const CallButtons = memo(CallButtonsComponent);

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
  },
});
