import React, { useEffect, useRef, useState, useCallback } from 'react';
import { View, StyleSheet, Image, Animated, useColorScheme } from 'react-native';
import * as SplashScreen from 'expo-splash-screen';

interface AnimatedSplashProps {
  onFinish: () => void;
}

export default function AnimatedSplash({ onFinish }: AnimatedSplashProps) {
  const fadeAnim = useRef(new Animated.Value(1)).current;
  const [isAppReady, setAppReady] = useState(false);
  const [isLayoutReady, setLayoutReady] = useState(false);
  const colorScheme = useColorScheme();
  const isDark = colorScheme === 'dark';

  useEffect(() => {
    async function prepare() {
      try {
        await new Promise(resolve => setTimeout(resolve, 1000));
      } catch (e) {
        console.warn(e);
      } finally {
        setAppReady(true);
      }
    }

    prepare();
  }, []);

  const onLayoutRootView = useCallback(async () => {
    setLayoutReady(true);
  }, []);

  useEffect(() => {
    if (isAppReady && isLayoutReady) {
      // Hide native splash screen
      SplashScreen.hideAsync();

      // Start fade out
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 1000,
        useNativeDriver: true,
      }).start(() => {
        onFinish();
      });
    }
  }, [isAppReady, isLayoutReady]);

  return (
    <Animated.View
      style={[
        styles.container,
        {
          opacity: fadeAnim,
          backgroundColor: isDark ? '#000000' : '#ffffff'
        }
      ]}
      onLayout={onLayoutRootView}
    >
      <View style={styles.centered}>
        <Image
          source={
            isDark
              ? require('../../assets/icons/splash-icon-light.png')
              : require('../../assets/icons/splash-icon-dark.png')
          }
          style={styles.logo}
          resizeMode="contain"
        />
      </View>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 9999,
  },
  centered: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    width: '100%',
    height: '100%',
  },
  logo: {
    width: '100%',
    height: '100%',
  }
});
