import React, { useState } from 'react';
import { View, Text, TouchableOpacity, FlatList, StyleSheet } from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { getFontSize } from 'src/utils';
import { Colors } from 'src/theme';
import { CustomMessage, Reaction } from '../types';
import { findMsgRecord } from '../ChatScreen';
import {
  addMessageDirtyAction,
  triggerMessagePush
} from 'src/watermelondb/features/chat/data/message.sync';
import { database } from 'src/watermelondb';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import { findGroupMsgRecord } from '../GroupChatScreen';

const ReactionsListModal = () => {
  const [reactionsData, setReactionsData] = useState<{
    users: { uid: number; name: string; reaction: string }[];
    currentUserId: number;
    token: string;
    messageId: number;
    conversation_with_user: number;
    setMessages: (messages: any) => void;
    sendWebSocketMessage: (action: string, data: any) => void;
    isGroup?: boolean;
    groupToken?: string;
  } | null>(null);

  const navigation = useNavigation();

  const handleSheetOpen = (
    payload: {
      users: { uid: number; name: string; reaction: string }[];
      currentUserId: number;
      token: string;
      messageId: number;
      conversation_with_user: number;
      setMessages: (messages: any) => void;
      sendWebSocketMessage: (action: string, data: any) => void;
      isGroup?: boolean;
      groupToken?: string;
    } | null
  ) => {
    setReactionsData(payload);
  };

  const handleUnreact = async () => {
    if (reactionsData) {
      if (reactionsData.isGroup) {
        const existingMsg = await findGroupMsgRecord(
          reactionsData.messageId,
          reactionsData.groupToken as string
        );

        if (existingMsg) {
          const messageReactions = existingMsg.reactions ? JSON.parse(existingMsg.reactions) : null;
          const updatedReactions: Reaction[] = Array.isArray(messageReactions)
            ? messageReactions?.filter((r: Reaction) => r.uid !== reactionsData.currentUserId)
            : [];

          await database.write(async () =>
            existingMsg.update((r) => {
              r.reactions = JSON.stringify(updatedReactions);
              addMessageDirtyAction(r, {
                type: 'unreaction'
              });
            })
          );
        }

        reactionsData.sendWebSocketMessage('unreact', {
          _id: reactionsData.messageId
        } as unknown as CustomMessage);

        SheetManager.hide('reactions-list-modal');
        await triggerMessagePush(reactionsData.token);
      } else {
        const existingMsg = await findMsgRecord(
          reactionsData.messageId,
          reactionsData.conversation_with_user
        );

        if (existingMsg) {
          const messageReactions = existingMsg.reactions ? JSON.parse(existingMsg.reactions) : null;
          const updatedReactions: Reaction[] = Array.isArray(messageReactions)
            ? messageReactions?.filter((r: Reaction) => r.uid !== reactionsData.currentUserId)
            : [];

          await database.write(async () =>
            existingMsg.update((r) => {
              r.reactions = JSON.stringify(updatedReactions);
              addMessageDirtyAction(r, {
                type: 'unreaction'
              });
            })
          );
        }

        reactionsData.sendWebSocketMessage('unreact', {
          _id: reactionsData.messageId
        } as unknown as CustomMessage);

        SheetManager.hide('reactions-list-modal');
        await triggerMessagePush(reactionsData.token);
      }
    }
  };

  return (
    <ActionSheet
      id="reactions-list-modal"
      gestureEnabled={true}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
      indicatorStyle={{ backgroundColor: Colors.FILL_LIGHT }}
    >
      <View style={styles.container}>
        <FlatList
          data={reactionsData?.users || []}
          keyExtractor={(item) => item.uid?.toString()}
          renderItem={({ item }) => {
            const isUserReacted = item.uid === reactionsData?.currentUserId;
            return (
              <TouchableOpacity
                style={styles.userItem}
                onPress={() => {
                  if (isUserReacted) {
                    handleUnreact();
                  } else {
                    SheetManager.hide('reactions-list-modal');

                    navigation.navigate(
                      ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: item.uid }] as never)
                    );
                  }
                }}
              >
                <View style={{ gap: 2 }}>
                  <Text style={styles.userName}>{item.name}</Text>
                  {isUserReacted && <Text style={styles.unreactText}>Tap to unreact</Text>}
                </View>
                <Text style={styles.reaction}>{item.reaction}</Text>
              </TouchableOpacity>
            );
          }}
        />
      </View>
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  sheetContainer: {
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15,
    padding: 16,
    paddingTop: 0,
    height: '40%'
  },
  container: {
    paddingTop: 12
  },
  userItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: Colors.FILL_LIGHT
  },
  userName: {
    fontSize: getFontSize(14),
    color: Colors.DARK_BLUE,
    fontFamily: 'montserrat-600'
  },
  reaction: {
    fontSize: 20
  },
  unreactText: {
    color: Colors.LIGHT_GRAY,
    fontSize: getFontSize(12),
    fontWeight: '600'
  }
});

export default ReactionsListModal;
