import React, {useEffect, useRef} from 'react';
import {View, Pressable} from 'react-native';
import {useTranslation} from 'react-i18next';
import * as Animatable from 'react-native-animatable';
import {Icon} from '@tabler/icons-react-native';
import {ListRow} from '@components/_HuGo/List';
import {Title} from '@components/_HuGo/Title';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {useTheme} from '@shared/theme';
import {BACKDROP} from '@shared/styles';

import {styles} from './styles';

interface Props {
  isVisible: boolean;
  onClose: () => void;
  onOptionPress: (key: string) => void;
  options: {key: string; label: string; Icon?: Icon}[];
}

export function ImageMenu({isVisible, onClose, onOptionPress, options}: Props) {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const paddingBottom = useSafeAreaBottomPadding();
  const animatableRef = useRef<Nullable<Animatable.View & View>>(null);

  const onItemPress = (key: string) => () => {
    onClose();
    onOptionPress(key);
  };

  useEffect(() => {
    if (animatableRef.current) {
      isVisible
        ? animatableRef.current.slideInUp!(200)
        : animatableRef.current.slideInDown!(200);
    }
  }, [isVisible, animatableRef]);

  return isVisible ? (
    <View style={styles.container}>
      <Pressable
        style={[
          styles.overlay,
          isVisible && {
            backgroundColor: BACKDROP.color,
            opacity: BACKDROP.opacity,
          },
        ]}
        onPress={onClose}
      />
      <Animatable.View
        ref={animatableRef}
        style={[
          styles.modal,
          {backgroundColor: theme.background.layout.tertiary, paddingBottom},
        ]}>
        <View
          style={[
            styles.indicator,
            {backgroundColor: theme.background.elements.grey},
          ]}
        />
        <Title center title={t('general.options')} />
        {options.map(option => (
          <ListRow key={option.key} onPress={onItemPress(option.key)}>
            <ListRow.Avatar Icon={option.Icon} />
            <ListRow.Title title={t(option.label)} />
          </ListRow>
        ))}
      </Animatable.View>
    </View>
  ) : null;
}
