import {memo, useEffect, useState} from 'react';
import {StyleSheet, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import Animated, {FadeIn, FadeOut} from 'react-native-reanimated';
import {IconX} from '@tabler/icons-react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {Portal} from '@gorhom/portal';
import {Pressable, Typography} from '@components';
import {useAiSummary} from '@modules/chats/contexts';
import {CHATS_SPACING} from '@modules/chats/utils';
import {CHATS_LOCAL_STORAGE_KEYS} from '@modules/chats/constants';
import {
  getItemFromStorageSync,
  setItemFromStorageSync,
} from '@services/localStorage';
import {useTheme, BORDER_RADIUS, SPACING} from '@shared/theme';

import {AI_SUMMARY_BUTTON_SIZE} from './AiSummaryButton';

const TRIANGLE_SIZE = SPACING.x3;
const CLOSE_BUTTON_SIZE = 24;

export const AiSummaryTooltip = memo(() => {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {bottom} = useSafeAreaInsets();
  const {buttonLayout} = useAiSummary();
  const [isVisible, setIsVisible] = useState(false);
  const xPosition = buttonLayout
    ? buttonLayout.x +
      AI_SUMMARY_BUTTON_SIZE / 2 +
      TRIANGLE_SIZE / 2 +
      SPACING['x0.5']
    : 0;
  const yPosition = CHATS_SPACING.inputContainerHeight + bottom + SPACING.x1;

  useEffect(() => {
    if (!xPosition) {
      return;
    }

    const tooltipViewed =
      getItemFromStorageSync({
        key: CHATS_LOCAL_STORAGE_KEYS.AiSummaryTooltipViewed,
        isObject: false,
      }) ?? false;

    if (!tooltipViewed) {
      setIsVisible(true);
      setItemFromStorageSync({
        key: CHATS_LOCAL_STORAGE_KEYS.AiSummaryTooltipViewed,
        value: 'true',
        isObject: false,
      });
    }
  }, [xPosition]);

  if (!xPosition || !isVisible) {
    return null;
  }

  const onClose = () => {
    setIsVisible(false);
  };

  return (
    <Portal hostName="root">
      <Pressable onPress={onClose} style={styles.overlay} useGestureHandler>
        {null}
      </Pressable>
      <Animated.View
        entering={FadeIn.delay(500)}
        exiting={FadeOut}
        onStartShouldSetResponder={() => true}
        style={[
          styles.container,
          {
            bottom: yPosition,
          },
        ]}>
        <View
          style={[
            styles.content,
            {backgroundColor: theme.background.elements.inverted},
          ]}>
          <View style={styles.header}>
            <Typography
              color={theme.text.neutral.inverted}
              variant="s"
              weight="semiBold"
              style={styles.title}>
              {t('chat.voicenote_ceo.tooltip.title')}
            </Typography>
            <Pressable
              onPress={onClose}
              style={[
                styles.closeButton,
                {backgroundColor: theme.button.background.tertiary.hover},
              ]}
              useGestureHandler>
              <IconX size={16} color={theme.background.elements.inverted} />
            </Pressable>
          </View>
          <Typography color={theme.text.neutral.inverted} variant="xs">
            {t('chat.voicenote_ceo.tooltip.description')}
          </Typography>
          <View
            style={[
              styles.triangle,
              {
                backgroundColor: theme.background.elements.inverted,
                left: xPosition,
              },
            ]}
          />
        </View>
      </Animated.View>
    </Portal>
  );
});

const styles = StyleSheet.create({
  overlay: {
    ...StyleSheet.absoluteFillObject,
    zIndex: 1,
  },
  container: {
    borderRadius: BORDER_RADIUS.l,
    left: SPACING.x3,
    right: SPACING.x3,
    position: 'absolute',
    zIndex: 2,
  },
  content: {
    borderRadius: BORDER_RADIUS.l,
    padding: SPACING.x2,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
    gap: SPACING.x1,
  },
  title: {
    flex: 1,
  },
  closeButton: {
    alignItems: 'center',
    height: CLOSE_BUTTON_SIZE,
    justifyContent: 'center',
    width: CLOSE_BUTTON_SIZE,
    borderRadius: BORDER_RADIUS.m,
  },
  triangle: {
    height: TRIANGLE_SIZE,
    overflow: 'hidden',
    position: 'absolute',
    width: TRIANGLE_SIZE,
    zIndex: -1,
    bottom: -TRIANGLE_SIZE / 2 + 1,
    transform: [{rotate: '45deg'}],
  },
});
