import React, {FC, memo, useCallback, useMemo, useState} from 'react';
import {View} from 'react-native';
import unescape from 'lodash.unescape';
import * as TablerIcons from '@tabler/icons-react-native';
import {
  Avatar,
  HtmlRender,
  IconButton,
  Pressable,
  Typography,
} from '@components';
import {
  Notification,
  NotificationIconType,
} from '@modules/notificationsCenter/interfaces';
import {
  useNotificationOptions,
  useGetModuleName,
} from '@modules/notificationsCenter/hooks';
import {MODULE_ICON} from '@modules/notificationsCenter/constants';
import {useInstanceId, useUserId} from '@redux/selectors';
import {useTheme} from '@shared/theme';
import {getTimeAgo, logAmplitudeEvent, openUrlFromApp} from '@shared/utils';
import {AMPLITUDE_EVENTS} from '@shared/constants';

import {NotificationOptionsDialog} from '../NotificationOptionsDialog';
import {styles} from './styles';

interface Props {
  item: Notification;
  listIsRead?: boolean;
}

function NotificationItem({item, listIsRead}: Props) {
  const {theme} = useTheme();
  const instanceId = useInstanceId();
  const userId = useUserId();
  const [optionsDialogIsVisible, setOptionsDialogIsVisible] = useState(false);
  const backgroundColor = item.isRead
    ? theme.background.layout.tertiary
    : theme.background.layout.brand;

  const {toggleReadNotification} = useNotificationOptions({
    id: item.id,
    module: item.module,
    listIsRead,
  });
  const onCloseOptionsDialog = () => setOptionsDialogIsVisible(false);
  const onPressMore = () => setOptionsDialogIsVisible(true);

  const onPressItem = useCallback(() => {
    if (item.deepLink) {
      openUrlFromApp(item.deepLink);
    }
    logAmplitudeEvent(AMPLITUDE_EVENTS.NC_NOTIFICATION_OPEN, {
      userId,
      instanceId,
      module: item.module,
    });
    !item.isRead && toggleReadNotification({isRead: true});
  }, [instanceId, item, toggleReadNotification, userId]);

  const Icon = useMemo(
    () =>
      item.module in MODULE_ICON
        ? MODULE_ICON[item.module as keyof typeof MODULE_ICON]
        : TablerIcons.IconBell,
    [item.module],
  );

  const moduleName = useGetModuleName(item.module, item.language);

  const bottomText = useMemo(
    () => `${getTimeAgo(item.createdAt)} · ${moduleName}`,
    [item.createdAt, moduleName],
  );

  const secondAvatarIcon = useMemo(
    () =>
      item.icon?.source && item.icon.source in TablerIcons
        ? (TablerIcons[
            item.icon.source as keyof typeof TablerIcons
          ] as FC<TablerIcons.IconProps>)
        : TablerIcons.IconBell,
    [item.icon?.source],
  );

  return (
    <>
      <Pressable
        style={[
          styles.container,
          {borderBottomColor: theme.border.neutral.default},
        ]}
        onPress={onPressItem}
        backgroundColor={backgroundColor}>
        <View style={styles.avatarContainer}>
          <Avatar url={item.imageUrl} Icon={Icon} size="md" variant="primary" />
          {item.icon && (
            <View
              style={[
                styles.secondAvatarContainer,
                {backgroundColor: theme.button.background.tertiary.hover},
              ]}>
              {item.icon.type === NotificationIconType.REACTION ? (
                <Typography
                  style={styles.reactionStyle}
                  weight="semiBold"
                  adjustsFontSizeToFit>
                  {item.icon.source}
                </Typography>
              ) : (
                <Avatar
                  url={item.icon.source}
                  Icon={secondAvatarIcon}
                  size="xs"
                  variant={item.icon.bgColor || 'default'}
                />
              )}
            </View>
          )}
        </View>
        <View style={styles.textContainer}>
          {item.text ? (
            <HtmlRender html={item.text} numberOfLines={4} />
          ) : (
            <>
              <Typography variant="xs" weight="semiBold" numberOfLines={2}>
                {unescape(item.title)}
              </Typography>
              {item.description && (
                <Typography variant="xs" numberOfLines={2}>
                  {unescape(item.description)}
                </Typography>
              )}
            </>
          )}
          <Typography variant="xxs" color={theme.text.neutral.brand}>
            {bottomText}
          </Typography>
        </View>
        <View>
          <IconButton
            Icon={TablerIcons.IconDotsVertical}
            onPress={onPressMore}
            variant="tertiary"
            size="lg"
          />
        </View>
      </Pressable>
      <NotificationOptionsDialog
        isRead={item.isRead}
        isVisible={optionsDialogIsVisible}
        onToggleReadNotification={toggleReadNotification}
        onClose={onCloseOptionsDialog}
      />
    </>
  );
}

export default memo(NotificationItem);
