import React, {useEffect, useRef} from 'react';
import {Animated, StyleSheet, Text} from 'react-native';
import {colors} from '../../utils/colors';

interface Props {
  message: string;
  visible: boolean;
  type?: 'success' | 'error' | 'info';
  onHide?: () => void;
}

export default function Toast({message, visible, type = 'info', onHide}: Props) {
  const opacity = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (visible) {
      Animated.sequence([
        Animated.timing(opacity, {toValue: 1, duration: 200, useNativeDriver: true}),
        Animated.delay(2500),
        Animated.timing(opacity, {toValue: 0, duration: 300, useNativeDriver: true}),
      ]).start(() => onHide?.());
    }
  }, [visible, opacity, onHide]);

  const bgColor =
    type === 'success'
      ? colors.success
      : type === 'error'
      ? colors.error
      : colors.surfaceHighlight;

  if (!visible) return null;

  return (
    <Animated.View style={[styles.toast, {backgroundColor: bgColor, opacity}]}>
      <Text style={styles.text}>{message}</Text>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  toast: {
    position: 'absolute',
    bottom: 80,
    alignSelf: 'center',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 24,
    maxWidth: '80%',
    zIndex: 9999,
    elevation: 10,
  },
  text: {
    color: colors.textPrimary,
    fontSize: 14,
    fontWeight: '500',
    textAlign: 'center',
  },
});
