import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View, Pressable } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { createContext, useState, useContext } from "react";
import { SafeAreaProvider } from "react-native-safe-area-context";

import MediaPlayer from "./src/components/MediaPlayer";

import HomeScreen from "./src/screens/HomeScreen";
import LikedTracksScreen from "./src/screens/LikedTracksScreen";
import AlbumScreen from "./src/screens/AlbumScreen";
import LoginScreen from "./src/screens/LoginScreen";
import PasswordResetScreen from "./src/screens/PasswordResetScreen";
import SettingsScreen from "./src/screens/SettingsScreen";
import SignUpScreen from "./src/screens/SignUpScreen";

import { LibraryProvider } from "./src/contexts/LibraryContext";


const Stack = createNativeStackNavigator();

const playerContext = createContext(null);

export function UsePlayer() {
  return useContext(playerContext);
}

function PlayerProvider({ children }) {
  const [currentTrack, setCurrentTrack] = useState();

  const [isPlaying, setIsPlaying] = useState(false);

  return (
    <playerContext.Provider
      value={{ currentTrack, setCurrentTrack, isPlaying, setIsPlaying }}
    >
      {children}
    </playerContext.Provider>
  );
}

function AppNavigator() {
  return (
    <NavigationContainer>
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="LikedTracks" component={LikedTracksScreen} />
        <Stack.Screen name="Album" component={AlbumScreen} />
        <Stack.Screen name="SignUp" component={SignUpScreen} />
        <Stack.Screen name="Login" component={LoginScreen} />
        <Stack.Screen name="PasswordReset" component={PasswordResetScreen} />
        <Stack.Screen name="Settings" component={SettingsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

function RootLayout() {
  const { currentTrack } = UsePlayer();

  return (
    <SafeAreaProvider style={styles.container}>
      <StatusBar style="auto" />

      <AppNavigator />

      <View style={styles.mediaPlayerWrapper} pointerEvents="box-none">
        <MediaPlayer title={currentTrack?.title ?? "No track"} />
      </View>
    </SafeAreaProvider>
  );
}

export default function App() {
  return (
    <PlayerProvider>
      <LibraryProvider>
        <RootLayout />
      </LibraryProvider>
    </PlayerProvider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#000",
  },
  mediaPlayerWrapper: {
    position: "absolute",
    left: 16,
    right: 16,
    bottom: 16,
    zIndex: 999,
    elevation: 10,
    pointerEvents: "box-none",
  },
});
