import React, {PropsWithChildren, useEffect, useMemo} from 'react';
import {StyleSheet, View, ViewStyle} from 'react-native';
import {KeyboardStickyView} from 'react-native-keyboard-controller';
import * as Sentry from '@sentry/react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import Animated from 'react-native-reanimated';
import {PortalHost} from '@gorhom/portal';
import {Navigation} from '@interfaces/navigation';
import {
  useClearNotifications,
  useSetupConversation,
  usePerformanceMetrics,
} from '@modules/chats/hooks';
import {
  InputValueProvider,
  MentionsProvider,
  MessageActionsProvider,
  MessagesListRefProvider,
  AiSummaryProvider,
  AudioRecordingProvider,
} from '@modules/chats/contexts';
import {CHAT_PORTAL_HOST_NAME} from '@modules/chats/constants';
import {DialogMentionMembers} from '@modules/chats/screens/ChatMessages/components/DialogMentionMembers';
import {AudioPlayerProvider} from '@modules/chats/contexts/AudioPlayerContext';
import {VideoPlayerPool} from '@modules/chats/instances/VideoPlayerPool';
import {VisibleVideoAssets} from '@modules/chats/instances/VisibleVideoAssets';
import {useTheme} from '@shared/theme';
import {Screens} from '@shared/constants';
import {isAndroid} from '@shared/utils';

import {ChatHeader} from './components/ChatHeader';
import Messages from './components/Messages';
import {AnimationProvider} from './components/ChatFooter/components/AnimationProvider';
import {MessageActions} from './components/MessageActions';
import DialogReactionList from './components/DialogReactionList';
import {ChatFooter} from './components/ChatFooter';
import EditionBackground from './components/EditionBackground';
import {DialogForwardMessage} from './components/DialogForwardMessage';
import {
  KeyboardOffsetStyleProvider,
  useKeyboardOffsetStyleContext,
} from './components/KeyboardOffsetStyleProvider';
import {PinnedMessages} from './components/PinnedMessages';

function KeyboardOffsetWrapperAndroid({
  children,
  style,
}: PropsWithChildren & {style?: ViewStyle}) {
  const offsetStyle = useKeyboardOffsetStyleContext();

  return <Animated.View style={[style, offsetStyle]}>{children}</Animated.View>;
}

function KeyboardOffsetWrapperIOS({
  children,
  style,
}: PropsWithChildren & {style?: ViewStyle}) {
  const {bottom} = useSafeAreaInsets();
  return (
    <KeyboardStickyView offset={{opened: bottom}} style={style}>
      {children}
    </KeyboardStickyView>
  );
}

const KeyboardOffsetWrapper = React.memo(
  isAndroid ? KeyboardOffsetWrapperAndroid : KeyboardOffsetWrapperIOS,
);

function ChatMessagesScreenComponent({
  route: {
    params: {id, initialMessage},
  },
}: Navigation<Screens.CHAT_MESSAGES>) {
  const showE2EMarker = usePerformanceMetrics();

  const {theme} = useTheme();

  useSetupConversation({channel: id});
  useClearNotifications();

  // Release every pooled `VideoPlayer` native instance when the chat
  // screen unmounts. Individual tile unmounts only mark slots idle —
  // this is what actually frees memory + ends any straggler buffering.
  // Also reset the visibility tracker so a new chat doesn't see stale
  // viewport state on its first render.
  useEffect(
    () => () => {
      VideoPlayerPool.clear();
      VisibleVideoAssets.clear();
    },
    [],
  );

  const memoizedContainerStyles = useMemo(() => {
    return [
      styles.container,
      {backgroundColor: theme.background.layout.default},
    ];
  }, [theme.background.layout.default]);

  return (
    <MessageActionsProvider>
      <AudioPlayerProvider>
        <KeyboardOffsetStyleProvider>
          <View
            testID={showE2EMarker ? 'chat-messages-loaded-marker' : undefined}
            style={styles.container}>
            <View style={memoizedContainerStyles}>
              <ChatHeader channel={id} />
              <MessagesListRefProvider>
                <View style={styles.container}>
                  <PinnedMessages channel={id} />
                  <Messages channel={id} />
                  <InputValueProvider
                    channel={id}
                    initialValue={initialMessage}>
                    <MentionsProvider>
                      <AnimationProvider>
                        <EditionBackground />
                        <DialogMentionMembers channel={id} />
                        <KeyboardOffsetWrapper>
                          <AudioRecordingProvider>
                            <AiSummaryProvider>
                              <ChatFooter channel={id} />
                            </AiSummaryProvider>
                          </AudioRecordingProvider>
                        </KeyboardOffsetWrapper>
                      </AnimationProvider>
                    </MentionsProvider>
                  </InputValueProvider>
                </View>
              </MessagesListRefProvider>
            </View>
            <MessageActions channel={id} />
            <DialogReactionList />
          </View>
          <PortalHost name={CHAT_PORTAL_HOST_NAME.messages} />
        </KeyboardOffsetStyleProvider>
      </AudioPlayerProvider>
      <DialogForwardMessage />
    </MessageActionsProvider>
  );
}

export const ChatMessagesScreen = Sentry.withProfiler(
  ChatMessagesScreenComponent,
  {
    name: 'Chats2.ChatMessagesScreen',
  },
);

const styles = StyleSheet.create({
  container: {flex: 1},
});
