import React, { useState } from 'react';
import { View, Text, TouchableOpacity, FlatList, StyleSheet } from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { usePostUnreactToMessageMutation } from '@api/chat';
import { getFontSize } from 'src/utils';
import { Colors } from 'src/theme';
import { CustomMessage } from '../types';

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;
  } | null>(null);

  const { mutateAsync: unreactToMessage } = usePostUnreactToMessageMutation();

  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;
    } | null
  ) => {
    setReactionsData(payload);
  };

  const handleUnreact = () => {
    if (reactionsData) {
      unreactToMessage(
        {
          token: reactionsData.token,
          message_id: reactionsData.messageId,
          conversation_with_user: reactionsData.conversation_with_user
        },
        {
          onSuccess: () => {
            SheetManager.hide('reactions-list-modal');
            reactionsData.setMessages((prevMessages: any) =>
              prevMessages?.map((msg: any) => {
                if (msg._id === reactionsData.messageId) {
                  return {
                    ...msg,
                    reactions: Array.isArray(msg.reactions)
                      ? msg.reactions.filter((r: any) => r.uid !== reactionsData.currentUserId)
                      : []
                  };
                }
                return msg;
              })
            );
            reactionsData.sendWebSocketMessage('unreact', {
              _id: reactionsData.messageId
            } as unknown as CustomMessage);
          }
        }
      );
    }
  };

  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={handleUnreact}
                disabled={!isUserReacted}
              >
                <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;
