import React, {useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconPhone, IconSearch, IconVideo} from '@tabler/icons-react-native';
import {useNavigation} from '@react-navigation/native';
import {CardContainer, ListRow, Pressable, Typography} from '@components';
import {
  openChatMessagesSearch,
  useShallowConversation,
} from '@modules/chats/store';
import {useCallInChannel} from '@modules/chats/hooks';
import {useStartCall} from '@modules/calls/hooks';
import {DialogMissingCallPermission} from '@modules/calls/components';
import {useHasActiveCall} from '@modules/calls/store/selectors';
import {useTheme} from '@shared/theme';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';
import {logAmplitudeEvent} from '@shared/utils';
import {useFeatureFlag} from '@stores/featureFlags';

import {styles} from './styles';

interface Props {
  channel: string;
}

export function ChatActionButtons({channel}: Props) {
  const {t} = useTranslation();
  const navigation = useNavigation();
  const [showMissingCallPermissions, setShowMissingCallPermissions] =
    useState(false);
  const conversation = useShallowConversation(channel, state => ({
    is_channel: !!state.is_channel,
    name: state.name,
  }));
  const hasActiveCall = useHasActiveCall();
  const {
    callId,
    externalCallId,
    isOngoingCall,
    isCallEnabled,
    isAudioCall,
    isVideoCall,
  } = useCallInChannel(channel);

  const {startVideoCall, startAudioCall, isCreatingCall} = useStartCall({
    channel,
    isGroup: !!conversation?.is_channel,
    groupName: conversation?.name,
    onRefusePermissions: () => {},
  });
  const isSearchEnabled = useFeatureFlag('CHATS_V2_SEARCH_IN_CHAT');
  const {theme, iconSizes} = useTheme();
  const colorDefault = theme.text.neutral.brand;
  const colorDisabled = theme.text.neutral.disabled;
  const colorOngoing = theme.button.background.success.focus;
  const isCallButtonDisabled = hasActiveCall || isCreatingCall;
  const callButtonColors = {
    audio: colorDefault,
    video: colorDefault,
  };

  if (isCallButtonDisabled) {
    callButtonColors.audio = colorDisabled;
    callButtonColors.video = colorDisabled;
  } else if (isAudioCall) {
    callButtonColors.audio = colorOngoing;
    callButtonColors.video = colorDisabled;
  } else if (isVideoCall) {
    callButtonColors.audio = colorDisabled;
    callButtonColors.video = colorOngoing;
  }

  const closeDialog = () => {
    setShowMissingCallPermissions(false);
  };

  const joinToCall = () => {
    if (!callId || !externalCallId) {
      return;
    }

    navigation.navigate(Screens.CALLS_CALL, {
      callId,
      isCaller: false,
      externalCallId,
    });
  };

  const onAudioCallPress = () => {
    // Redirect to ongoing call if it exists
    if (isOngoingCall) {
      joinToCall();
      return;
    }

    // Start new call
    startAudioCall();
  };

  const onVideoCallPress = () => {
    // Redirect to ongoing call if it exists
    if (isOngoingCall) {
      joinToCall();
      return;
    }

    // Start new call
    startVideoCall();
  };

  const onSearchPress = () => {
    openChatMessagesSearch();
    navigation.goBack();
    logAmplitudeEvent(AMPLITUDE_EVENTS.CHATS_2_CONVERSATION_SEARCH_STARTED, {
      channel,
    });
  };

  return (
    <>
      <View style={styles.container}>
        {isCallEnabled && (
          <>
            <CardContainer style={styles.buttonContainer}>
              <Pressable
                style={styles.button}
                onPress={onAudioCallPress}
                disabled={isVideoCall || isCallButtonDisabled}>
                <IconPhone color={callButtonColors.audio} size={iconSizes.x6} />
                <Typography color={callButtonColors.audio} weight="semiBold">
                  {t(isAudioCall ? 'calls.join' : 'profile.call')}
                </Typography>
              </Pressable>
            </CardContainer>
            <CardContainer style={styles.buttonContainer}>
              <Pressable
                style={styles.button}
                onPress={onVideoCallPress}
                disabled={isAudioCall || isCallButtonDisabled}>
                <IconVideo color={callButtonColors.video} size={iconSizes.x6} />
                <Typography color={callButtonColors.video} weight="semiBold">
                  {t(isVideoCall ? 'calls.join' : 'general.video')}
                </Typography>
              </Pressable>
            </CardContainer>
          </>
        )}
        {isSearchEnabled && (
          <>
            {isCallEnabled ? (
              <CardContainer style={styles.buttonContainer}>
                <Pressable style={styles.button} onPress={onSearchPress}>
                  <IconSearch
                    color={theme.text.neutral.brand}
                    size={iconSizes.x6}
                  />
                  <Typography
                    color={theme.text.neutral.brand}
                    weight="semiBold">
                    {t('general.search')}
                  </Typography>
                </Pressable>
              </CardContainer>
            ) : (
              <CardContainer>
                <ListRow onPress={onSearchPress}>
                  <ListRow.Avatar Icon={IconSearch} variant="primary" />
                  <ListRow.Title
                    title={t('chat.search.by_message')}
                    variant="primaryTitle"
                  />
                  <ListRow.SideContent withRightIcon />
                </ListRow>
              </CardContainer>
            )}
          </>
        )}
      </View>
      <DialogMissingCallPermission
        isVisible={showMissingCallPermissions}
        onClose={closeDialog}
      />
    </>
  );
}
