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 {IconName} from '@components/Icon';
import {BottomModalHeader, MenuItem} from '@components/Modals';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';

import {styles} from './styles';

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

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

  const handleItemPress = (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} onPress={onClose} />
      <Animatable.View
        ref={animatableRef}
        style={[styles.modal, {paddingBottom}]}>
        <View style={styles.indicator} />
        <BottomModalHeader title={t('general.options')} style={styles.header} />
        <View style={styles.paddingHorizontal}>
          {options.map((option, index) => (
            <MenuItem
              key={option.key}
              option={option}
              onPress={handleItemPress}
              isLast={index === options.length - 1}
            />
          ))}
        </View>
      </Animatable.View>
    </View>
  ) : null;
}
