import React, {useCallback, useMemo} from 'react';
import {Pressable, StyleSheet, View} from 'react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {shallowEqual} from 'react-redux';
import {useNavigation} from '@react-navigation/native';
import {Avatar, AvatarWithName} from '@components/Image';
import BackButton from '@components/BackButton';
import Icon from '@components/Icon';
import Text from '@components/Text';
import {useGoBack} from '@hooks/useGoBack';
import {Navigation} from '@interfaces/navigation';
import {GettingReadyType} from '@modules/commons/interfaces';
import {chatRowStyles} from '@modules/chat/components/ChatRow/constants';
import {getUserNamesConcatenated} from '@modules/chat/utils';
import {FormStepType} from '@modules/form/interfaces';
import {CallStartButtons} from '@modules/calls/components/CallStartButtons';
import InactiveFeatureButton from '@modules/commons/components/InactiveFeatureButton';
import {useTypingEvent} from '@modules/chat/hooks';
import {ChatListItem, ChatType} from '@modules/chat/interfaces';
import {MAX_CALL_PARTICIPANTS} from '@modules/calls/constants';
import {useAppSelector} from '@redux/utils';
import {SPACING} from '@shared/theme';
import {COLORS} from '@shared/colors';
import {Screens} from '@shared/constants';
import {useCommunityFeature} from '@stores/communityFeatures';

import {TicketActionButton} from '../TicketActionButton';

interface Props {
  chat?: ChatListItem;
  ticket?: {
    id: number;
    status: FormStepType;
  };
  isResponsible?: boolean;
}

export function ChatHeader({chat, ticket, isResponsible}: Props) {
  const chatId = chat?.chatId;
  const isRegularChat = chat?.chatType === ChatType.REGULAR;
  const isRegularGroup = chat?.chatType === ChatType.REGULAR_GROUP;
  const isTicket = chat?.chatType === ChatType.TICKET;
  const navigation = useNavigation<Navigation['navigation']>();
  const {goBack} = useGoBack();
  const {top} = useSafeAreaInsets();
  const showTicketActionButton =
    ticket && isResponsible && ticket?.status !== FormStepType.CLOSED;
  const {canViewDemoCalls, userId, instanceColor} = useAppSelector(
    ({instance, user}) => ({
      canViewDemoCalls:
        instance.allowChatCall && (isRegularChat || isRegularGroup),
      userId: user.id,
      instanceColor: instance.color,
    }),
    shallowEqual,
  );
  const canViewCalls = useCommunityFeature('VIEW_CALL');

  const {typingText} = useTypingEvent({
    chatId,
    chatType: chat?.chatType,
  });

  const otherUsersText = useMemo(
    () =>
      chat?.chat.otherUsers?.length
        ? getUserNamesConcatenated({
            users: chat?.chat.otherUsers,
            currentUserId: userId,
          })
        : '',
    [chat?.chat.otherUsers, userId],
  );

  const showGroupCallButtons = useMemo(
    () => (chat?.chat.otherUsers?.length ?? 0) <= MAX_CALL_PARTICIPANTS,
    [chat?.chat.otherUsers],
  );

  const groupCall = useMemo(
    () =>
      isRegularGroup
        ? {isGroupCall: isRegularGroup, callGroupName: chat?.title}
        : null,
    [chat, isRegularGroup],
  );

  const onGroupPress = useCallback(() => {
    chatId && navigation.navigate(Screens.CHAT_GROUP_INFO, {chatId});
  }, [chatId, navigation]);

  const onUserPress = useCallback(() => {
    const targetUserId = chat?.chat.otherUser?.id;
    targetUserId &&
      navigation.navigate(Screens.PROFILE, {userId: targetUserId});
  }, [chat?.chat.otherUser?.id, navigation]);

  return (
    <View style={[styles.container, !!top && {paddingTop: top}]}>
      <BackButton onPress={goBack} />
      {isRegularGroup ? (
        <Pressable onPress={onGroupPress} style={styles.content}>
          {chat?.pictureUrl ? (
            <Avatar
              style={chatRowStyles.avatar}
              url={chat.pictureUrl}
              size="md"
            />
          ) : (
            <View
              style={[
                chatRowStyles.avatar,
                {backgroundColor: chat?.color || COLORS.GRAY_EIGHT},
              ]}>
              <Icon size="md" name="groupsFill" color={COLORS.WHITE} />
            </View>
          )}
          <View style={styles.flex}>
            <Text variant="subtitle1" numberOfLines={1}>
              {chat?.title}
            </Text>
            <Text variant="caption" numberOfLines={1} color={COLORS.DARK_GRAY}>
              {typingText || otherUsersText}
            </Text>
          </View>
        </Pressable>
      ) : isRegularChat ? (
        <Pressable
          onPress={onUserPress}
          style={styles.content}
          disabled={chat.chat.otherUser?.deleted}>
          <AvatarWithName
            url={chat.chat.otherUser?.profilePicture}
            name={chat.chat.otherUser || ''}
            size="lg"
            detail={typingText || ''}
            flexDirection="column"
          />
        </Pressable>
      ) : isTicket ? (
        <View style={styles.content}>
          <View style={chatRowStyles.avatar}>
            <Icon name="tag" size="lg" />
            <Text
              numberOfLines={1}
              adjustsFontSizeToFit
              variant="caption"
              minimumFontScale={0}
              align="center"
              style={styles.topicId}>
              ID {chat.id}
            </Text>
          </View>
          <View style={styles.flex}>
            <View
              style={[
                styles.topicContainerStyle,
                {
                  backgroundColor: chat.topic.deleted
                    ? COLORS.DARK_GRAY
                    : instanceColor,
                },
              ]}>
              <Text
                variant="subtitle1"
                style={styles.topicTextStyle}
                numberOfLines={1}>
                {chat.topic.name}
              </Text>
            </View>
            {!!chat.subject && (
              <Text variant="caption" color={COLORS.DARK_GRAY}>
                {chat.subject}
              </Text>
            )}
          </View>
        </View>
      ) : null}
      {showTicketActionButton ? (
        <TicketActionButton ticketId={ticket.id} ticketStatus={ticket.status} />
      ) : canViewDemoCalls && showGroupCallButtons ? (
        <>
          <InactiveFeatureButton type={GettingReadyType.VideoCall} />
          <InactiveFeatureButton type={GettingReadyType.AudioCall} />
        </>
      ) : canViewCalls && showGroupCallButtons ? (
        <CallStartButtons chatId={chatId!} groupCall={groupCall} />
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    backgroundColor: COLORS.WHITE,
    alignItems: 'center',
    gap: SPACING.x1,
    paddingRight: SPACING.x2,
    paddingVertical: SPACING.x1,
    paddingLeft: 0,
    minHeight: 64,
  },
  content: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING.x1,
  },
  topicContainerStyle: {
    alignSelf: 'flex-start',
    borderRadius: 10,
    marginVertical: 3,
  },
  topicTextStyle: {
    borderRadius: 10,
    color: COLORS.WHITE,
    paddingHorizontal: 10,
    textAlign: 'center',
  },
  flex: {flex: 1},
  topicId: {paddingHorizontal: SPACING['x0.5'], marginTop: -SPACING['x0.5']},
});
