import { FC, useCallback, useEffect, useState } from 'react';
import { Container, SafeAreaView } from 'components';
import {
  useMultipleNotificationsQuery,
  NotificationFragment,
  useNotificationChangedSubscription,
} from 'expo-schema';
import { metrics } from 'config';
import { List } from 'components/notification';
import { Header } from './header';
const { STYLES, LIMITS } = metrics;

export const Inbox: FC = () => {
  const [notifications, setNotifications] = useState<NotificationFragment[]>([]);

  const { data } = useMultipleNotificationsQuery({
    variables: {
      limit: LIMITS.notifications,
      offset: 0,
    },
  });

  const isNotificationExist = useCallback(
    (notificationId: string) => {
      const notificationResponse = notifications.find(
        (notification) => notification.id === notificationId
      );
      return notificationResponse;
    },
    [notifications]
  );

  const updateNotification = useCallback(
    (notification: NotificationFragment) => {
      const index = notifications.findIndex((msg) => msg.id === notification.id);
      const updatedNotifications = [...notifications];
      updatedNotifications.splice(index, 1, notification);
      setNotifications(updatedNotifications);
    },
    [notifications]
  );
  const addNotification = useCallback(
    (notification: NotificationFragment) => {
      setNotifications([...notifications, notification]);
    },
    [notifications]
  );

  const handleSubscription = useCallback(
    (notification: NotificationFragment) => {
      if (notification) {
        if (isNotificationExist(notification.id)) {
          updateNotification(notification);
        } else {
          addNotification(notification);
        }
      }
    },
    [addNotification, isNotificationExist, updateNotification]
  );

  useNotificationChangedSubscription({
    onSubscriptionData: (sub) => {
      handleSubscription(sub.subscriptionData.data?.notificationChanged as NotificationFragment);
    },
  });
  useEffect(() => {
    if (data?.MultipleNotifications) {
      setNotifications(data?.MultipleNotifications as NotificationFragment[]);
    }
    return () => {};
  }, [data?.MultipleNotifications]);

  return (
    <SafeAreaView>
      <Header />
      <Container width={STYLES.sideBarWidth}>
        <List variant="float" notifications={notifications as NotificationFragment[]} />
      </Container>
    </SafeAreaView>
  );
};
