import React, { useEffect, useRef, useState } from 'react';
import { Animated, Image, StyleSheet, Text, View } from 'react-native';
import * as SplashScreen from 'expo-splash-screen';
import images from '@/constants/images';

interface SplashScreenOverlayProps {
  onFinish?: () => void;
}

export function SplashScreenOverlay({ onFinish }: SplashScreenOverlayProps) {
  const fadeAnim = useRef(new Animated.Value(1)).current;
  const scaleAnim = useRef(new Animated.Value(0.95)).current;
  const [isVisible, setIsVisible] = useState(true);

  useEffect(() => {
    // Hide native splash screen once component mounts
    SplashScreen.hideAsync().catch(() => {});

    // Smooth entry animation for logo & text
    Animated.parallel([
      Animated.timing(scaleAnim, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true,
      }),
    ]).start();

    // Fade out splash overlay after a short delay
    const timer = setTimeout(() => {
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 600,
        useNativeDriver: true,
      }).start(() => {
        setIsVisible(false);
        if (onFinish) onFinish();
      });
    }, 1800);

    return () => clearTimeout(timer);
  }, []);

  if (!isVisible) return null;

  return (
    <Animated.View style={[styles.container, { opacity: fadeAnim }]}>
      {/* Background radial/ellipse glow effect matching design */}
      <View style={styles.radialGlow} />

      {/* Content Container */}
      <Animated.View style={[styles.content, { transform: [{ scale: scaleAnim }] }]}>
        <View style={styles.logoContainer}>
          <Image
            source={images.logo}
            style={styles.logo}
            resizeMode="cover"
          />
        </View>
        <Text style={styles.welcomeText}>welcome to travelcam</Text>
      </Animated.View>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFill,
    backgroundColor: '#071126',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 99999,
  },
  radialGlow: {
    position: 'absolute',
    width: 380,
    height: 380,
    borderRadius: 190,
    backgroundColor: '#0E1F47',
    opacity: 0.6,
  },
  content: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 20,
  },
  logoContainer: {
    width: 150,
    height: 150,
    borderRadius: 30,
    overflow: 'hidden',
    marginBottom: 28,
    shadowColor: '#38BDF8',
    shadowOffset: { width: 0, height: 8 },
    shadowOpacity: 0.35,
    shadowRadius: 16,
    elevation: 10,
  },
  logo: {
    width: '100%',
    height: '100%',
    borderRadius: 30,
  },
  welcomeText: {
    color: '#FFFFFF',
    fontSize: 22,
    fontWeight: '500',
    letterSpacing: 0.5,
    textAlign: 'center',
  },
});
