import React, { useRef, useEffect } from 'react';
import { View, Text, StyleSheet, Modal, Animated, Pressable } from 'react-native';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

let _showAlert = null;

/**
 * Show a themed alert. Call from anywhere:
 *   import { showAlert } from '../components/NovaAlert';
 *   showAlert('Title', 'Message', [{ text: 'OK' }]);
 */
export function showAlert(title, message, buttons = [{ text: 'OK' }]) {
  if (_showAlert) _showAlert({ title, message, buttons });
}

export default function NovaAlertProvider({ children }) {
  const [alert, setAlert] = React.useState(null);
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const scaleAnim = useRef(new Animated.Value(0.85)).current;

  useEffect(() => {
    _showAlert = (data) => setAlert(data);
    return () => { _showAlert = null; };
  }, []);

  useEffect(() => {
    if (alert) {
      fadeAnim.setValue(0);
      scaleAnim.setValue(0.85);
      Animated.parallel([
        Animated.timing(fadeAnim, { toValue: 1, duration: 200, useNativeDriver: true }),
        Animated.spring(scaleAnim, { toValue: 1, useNativeDriver: true, speed: 20, bounciness: 8 }),
      ]).start();
    }
  }, [alert]);

  const dismiss = (callback) => {
    setAlert(null);
    if (callback) setTimeout(callback, 50);
  };

  return (
    <>
      {children}
      <Modal visible={!!alert} transparent animationType="none" statusBarTranslucent>
        <Animated.View style={[styles.overlay, { opacity: fadeAnim }]}>
          <Pressable style={styles.overlayPress} onPress={() => dismiss()} />
          <Animated.View style={[styles.card, { transform: [{ scale: scaleAnim }] }]}>
            {/* Accent line */}
            <View style={styles.accentLine} />

            {alert?.title && (
              <Text style={styles.title}>{alert.title}</Text>
            )}
            {alert?.message && (
              <Text style={styles.message}>{alert.message}</Text>
            )}

            <View style={styles.buttons}>
              {(alert?.buttons || []).map((btn, i) => {
                const isDestructive = btn.style === 'destructive';
                const isCancel = btn.style === 'cancel';
                const isLast = i === (alert?.buttons || []).length - 1;

                return (
                  <Pressable
                    key={i}
                    style={({ pressed }) => [
                      styles.button,
                      isCancel && styles.buttonCancel,
                      isDestructive && styles.buttonDestructive,
                      !isCancel && !isDestructive && styles.buttonPrimary,
                      pressed && styles.buttonPressed,
                      i > 0 && { marginLeft: spacing.sm },
                    ]}
                    onPress={() => dismiss(btn.onPress)}
                  >
                    <Text style={[
                      styles.buttonText,
                      isCancel && styles.buttonTextCancel,
                      isDestructive && styles.buttonTextDestructive,
                    ]}>
                      {btn.text}
                    </Text>
                  </Pressable>
                );
              })}
            </View>
          </Animated.View>
        </Animated.View>
      </Modal>
    </>
  );
}

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    alignItems: 'center',
    justifyContent: 'center',
    padding: spacing.xl,
  },
  overlayPress: {
    ...StyleSheet.absoluteFillObject,
  },
  card: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.xl,
    borderWidth: 1,
    borderColor: colors.border,
    width: '100%',
    maxWidth: 340,
    overflow: 'hidden',
  },
  accentLine: {
    height: 3,
    backgroundColor: colors.primary,
  },
  title: {
    color: colors.text,
    fontSize: fonts.sizes.lg,
    fontWeight: fonts.weights.bold,
    textAlign: 'center',
    paddingTop: spacing.xl,
    paddingHorizontal: spacing.lg,
  },
  message: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    textAlign: 'center',
    lineHeight: 22,
    paddingTop: spacing.md,
    paddingHorizontal: spacing.lg,
    paddingBottom: spacing.lg,
  },
  buttons: {
    flexDirection: 'row',
    paddingHorizontal: spacing.lg,
    paddingBottom: spacing.lg,
  },
  button: {
    flex: 1,
    paddingVertical: spacing.md,
    borderRadius: borderRadius.md,
    alignItems: 'center',
    justifyContent: 'center',
    minHeight: 44,
  },
  buttonPrimary: {
    backgroundColor: colors.primary,
  },
  buttonCancel: {
    backgroundColor: 'rgba(138, 143, 181, 0.1)',
    borderWidth: 1,
    borderColor: colors.border,
  },
  buttonDestructive: {
    backgroundColor: 'rgba(255, 82, 82, 0.12)',
    borderWidth: 1,
    borderColor: 'rgba(255, 82, 82, 0.3)',
  },
  buttonPressed: {
    opacity: 0.7,
  },
  buttonText: {
    color: colors.text,
    fontSize: fonts.sizes.md,
    fontWeight: fonts.weights.semibold,
  },
  buttonTextCancel: {
    color: colors.textSecondary,
  },
  buttonTextDestructive: {
    color: colors.error,
  },
});
