import React, { createContext, useState, useCallback, useContext } from 'react';
import { View, Text, StyleSheet, Animated, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../theme';
import { radii, spacing, shadows } from '../theme/spacing';
import { useResponsive } from '../hooks/useResponsive';

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

interface Toast {
  id: string;
  message: string;
  type: ToastType;
}

interface ToastContextType {
  toast: (message: string, type?: ToastType) => void;
}

const ToastContext = createContext<ToastContextType>({ toast: () => {} });

export function useToast() {
  return useContext(ToastContext);
}

const TOAST_CONFIG: Record<ToastType, { icon: keyof typeof Ionicons.glyphMap; bg: string; border: string }> = {
  success: { icon: 'checkmark-circle', bg: colors.success[50], border: colors.success[500] },
  error: { icon: 'close-circle', bg: colors.danger[50], border: colors.danger[500] },
  warning: { icon: 'warning', bg: colors.warning[50], border: colors.warning[500] },
  info: { icon: 'information-circle', bg: colors.info[50], border: colors.info[500] },
};

export function ToastProvider({ children }: { children: React.ReactNode }) {
  const [toasts, setToasts] = useState<Toast[]>([]);
  const { fontSize } = useResponsive();

  const toast = useCallback((message: string, type: ToastType = 'info') => {
    const id = Date.now().toString();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 3500);
  }, []);

  const dismiss = (id: string) => {
    setToasts(prev => prev.filter(t => t.id !== id));
  };

  return (
    <ToastContext.Provider value={{ toast }}>
      {children}
      <View style={styles.container} pointerEvents="box-none">
        {toasts.map(t => {
          const config = TOAST_CONFIG[t.type];
          return (
            <View key={t.id} style={[styles.toast, { backgroundColor: config.bg, borderLeftColor: config.border }]}>
              <Ionicons name={config.icon} size={20} color={config.border} />
              <Text style={[styles.message, { fontSize: fontSize.bodySmall }]} numberOfLines={2}>{t.message}</Text>
              <TouchableOpacity onPress={() => dismiss(t.id)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                <Ionicons name="close" size={16} color={colors.gray[400]} />
              </TouchableOpacity>
            </View>
          );
        })}
      </View>
    </ToastContext.Provider>
  );
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 50,
    left: spacing.lg,
    right: spacing.lg,
    zIndex: 9999,
    gap: spacing.sm,
  },
  toast: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: spacing.md,
    borderRadius: radii.lg,
    borderLeftWidth: 3,
    gap: spacing.sm,
    ...shadows.lg,
  },
  message: {
    flex: 1,
    fontWeight: '500',
    color: colors.gray[800],
  },
});
