import React, { useEffect, useRef, useState } from 'react';
import { Animated, Easing, SafeAreaView, StyleSheet, Text, TouchableOpacity } from 'react-native';
import Modal from 'react-native-modal';

interface AlertOption {
  label: string;
  onPress: () => void;
}

interface CustomAlertProps {
  visible?: boolean;
  options: AlertOption[];
  onClose?: () => void;
}

const CustomAlert: React.FC<CustomAlertProps> = ({ visible = true, options, onClose }) => {
  const [show, setShow] = useState(visible);
  const scaleAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (show) {
      Animated.spring(scaleAnim, {
        toValue: 1,
        useNativeDriver: true,
        friction: 5,
        tension: 50,
      }).start();
    }
  }, [show]);

  const closeModal = () => {
    Animated.timing(scaleAnim, {
      toValue: 0,
      duration: 200,
      easing: Easing.out(Easing.ease),
      useNativeDriver: true,
    }).start(() => {
      setShow(false);
      if (onClose) onClose();
    });
  };

  return (
    <SafeAreaView>
      <Modal
        isVisible={show}
        onBackdropPress={closeModal}
        backdropOpacity={0.5}
        animationIn="fadeIn"
        animationOut="fadeOut"
      >
        <Animated.View style={[styles.mainContainer, { transform: [{ scale: scaleAnim }] }]}>
          {options.map((option, index) => (
            <TouchableOpacity
              key={index}
              style={styles.option}
              onPress={() => {
                option.onPress();
                closeModal();
              }}
            >
              <Text style={styles.optionText}>{option.label}</Text>
            </TouchableOpacity>
          ))}
        </Animated.View>
      </Modal>
    </SafeAreaView>
  );
};

export default CustomAlert;

const styles = StyleSheet.create({
  mainContainer: {
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 16,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 12 },
    shadowOpacity: 0.58,
    shadowRadius: 16,
    elevation: 24,
  },
  option: {
    paddingVertical: 12,
    width: '100%',
    alignItems: 'center',
  },
  optionText: {
    fontSize: 16,
    color: '#333',
  },
});
