import React, {
  createContext,
  useContext,
  useState,
  useRef,
  useEffect,
} from 'react';
import {
  View,
  Text,
  StyleSheet,
  Animated,
  TouchableOpacity,
  Dimensions,
} from 'react-native';

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

type ToastOptions = {
  type?: ToastType;
  message: string;
  duration?: number;
};

type ToastContextType = {
  showToast: (options: ToastOptions) => void;
};

const ToastContext = createContext<ToastContextType | null>(null);

export const useToast = () => {
  const ctx = useContext(ToastContext);
  if (!ctx) {throw new Error('useToast must be used within a ToastProvider');}
  return ctx;
};

export const ToastProvider = ({children}: {children: React.ReactNode}) => {
  const [toast, setToast] = useState<ToastOptions | null>(null);
  const fadeAnim = useRef(new Animated.Value(0)).current;

  const showToast = (options: ToastOptions) => {
    setToast(options);
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 200,
      useNativeDriver: true,
    }).start();

    setTimeout(() => {
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }).start(() => setToast(null));
    }, options.duration || 3000);
  };

  const getToastStyle = (type: ToastType = 'info') => {
    switch (type) {
      case 'success':
        return {backgroundColor: '#38A169'};
      case 'error':
        return {backgroundColor: '#FF3E3E'};
      case 'info':
      default:
        return {backgroundColor: '#007aa5'};
    }
  };

  return (
    <ToastContext.Provider value={{showToast}}>
      {children}
      {toast && (
        <Animated.View
          style={[
            styles.toastContainer,
            getToastStyle(toast.type),
            {opacity: fadeAnim},
          ]}>
          <TouchableOpacity
            onPress={() => setToast(null)}
            activeOpacity={0.8}
            style={styles.toastContent}>
            <Text style={styles.toastText}>{toast.message}</Text>
          </TouchableOpacity>
        </Animated.View>
      )}
    </ToastContext.Provider>
  );
};

const styles = StyleSheet.create({
  toastContainer: {
    position: 'absolute',
    top: 50,
    left: 20,
    right: 20,
    borderRadius: 8,
    padding: 12,
    zIndex: 1000,
    elevation: 10,
    shadowColor: '#000',
    shadowOpacity: 0.3,
    shadowRadius: 5,
    shadowOffset: {width: 0, height: 2},
  },
  toastContent: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  toastText: {
    color: 'white',
    fontSize: 15,
    textAlign: 'center',
  },
});
