import React, { useEffect, useRef } from 'react';
import { StyleSheet, View, Text, Animated, TouchableOpacity, Dimensions, Platform } from 'react-native';
import { colors } from '@/constants/colors';
import { X, CheckCircle, AlertTriangle, Info } from 'lucide-react-native';
import { LinearGradient } from 'expo-linear-gradient';

export type ToastType = 'success' | 'error' | 'info' | 'warning';

interface ToastNotificationProps {
  visible: boolean;
  message: string;
  type: ToastType;
  onDismiss: () => void;
  autoClose?: boolean;
  duration?: number;
}

const { width } = Dimensions.get('window');

export default function ToastNotification({
  visible,
  message,
  type,
  onDismiss,
  autoClose = true,
  duration = 3000,
}: ToastNotificationProps) {
  const translateY = useRef(new Animated.Value(-100)).current;
  const opacity = useRef(new Animated.Value(0)).current;
  const scaleX = useRef(new Animated.Value(0.95)).current;
  const timeout = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (visible) {
      // Clear any existing timeout
      if (timeout.current) {
        clearTimeout(timeout.current);
      }

      // Show animation
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: 0,
          duration: 400,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(opacity, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(scaleX, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();

      // Auto close after duration
      if (autoClose) {
        timeout.current = setTimeout(() => {
          hideToast();
        }, duration);
      }
    } else {
      // Reset position when not visible
      translateY.setValue(-100);
      opacity.setValue(0);
      scaleX.setValue(0.95);
    }

    return () => {
      if (timeout.current) {
        clearTimeout(timeout.current);
      }
    };
  }, [visible]);

  const hideToast = () => {
    Animated.parallel([
      Animated.timing(translateY, {
        toValue: -100,
        duration: 300,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(opacity, {
        toValue: 0,
        duration: 200,
        useNativeDriver: Platform.OS !== 'web',
      }),
    ]).start(() => {
      onDismiss();
    });
  };

  const getToastStyles = () => {
    switch (type) {
      case 'success':
        return {
          backgroundColor: 'rgba(46, 204, 113, 0.95)',
          gradientColors: ['rgba(46, 204, 113, 0.95)', 'rgba(39, 174, 96, 0.95)'],
          icon: <CheckCircle size={20} color="#fff" />,
        };
      case 'error':
        return {
          backgroundColor: 'rgba(231, 76, 60, 0.95)',
          gradientColors: ['rgba(231, 76, 60, 0.95)', 'rgba(192, 57, 43, 0.95)'],
          icon: <X size={20} color="#fff" />,
        };
      case 'warning':
        return {
          backgroundColor: 'rgba(243, 156, 18, 0.95)',
          gradientColors: ['rgba(243, 156, 18, 0.95)', 'rgba(211, 84, 0, 0.95)'],
          icon: <AlertTriangle size={20} color="#fff" />,
        };
      case 'info':
      default:
        return {
          backgroundColor: 'rgba(41, 171, 226, 0.95)',
          gradientColors: ['rgba(41, 171, 226, 0.95)', 'rgba(52, 152, 219, 0.95)'],
          icon: <Info size={20} color="#fff" />,
        };
    }
  };

  const toastStyle = getToastStyles();

  if (!visible) return null;

  return (
    <Animated.View
      style={[
        styles.container,
        {
          opacity,
          ...(Platform.OS === 'web' 
            ? { top: 0 } 
            : { transform: [{ translateY }, { scaleX }] })
        },
      ]}
    >
      <LinearGradient
        colors={toastStyle.gradientColors}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 0 }}
        style={styles.gradient}
      />
      <View style={styles.content}>
        <View style={styles.iconContainer}>{toastStyle.icon}</View>
        <Text style={styles.message}>{message}</Text>
      </View>
      <TouchableOpacity style={styles.closeButton} onPress={hideToast}>
        <X size={16} color="#fff" />
      </TouchableOpacity>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    zIndex: 9999,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomLeftRadius: 12,
    borderBottomRightRadius: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 6,
    elevation: 8,
    width: width,
    overflow: 'hidden',
  },
  gradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  content: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  iconContainer: {
    marginRight: 12,
  },
  message: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '500',
    flex: 1,
  },
  closeButton: {
    padding: 4,
  },
});