import { createContext, useContext, useEffect, useState } from "react";
import { Platform } from "react-native";
import * as SecureStore from 'expo-secure-store'

interface AuthProps {
  authState?: {email: string | null; authenticated: boolean | null; session: string | null};
  isLoading?: boolean | null;
  onRegister?: (email: string, password: string) => Promise<any>;
  onLogin?: (email: string, password: string) => Promise<any>;
  onLogout?: () => void;
}

const SESSION_KEY = 'my_session'
const USER_KEY = "email"
const AuthContext = createContext<AuthProps>({})

export const useAuth = ()=>{
  return useContext(AuthContext)
}

async function setStorageItemAsync(key: string, value: string | null){
  if (Platform.OS === 'web') {
    try {
      if (value === null) {
        localStorage.removeItem(key);
      } else {
        localStorage.setItem(key, value);
      }
    } catch (e) {
      console.error('Local storage is unavailable:', e);
    }
  } else {
    if (value == null) {
      await SecureStore.deleteItemAsync(key);
    } else {
      await SecureStore.setItemAsync(key, value);
    }
  }
}

async function getStorageItemAsync(key: string) : Promise<string|null> {
   if(Platform.OS === 'web'){
    return localStorage.getItem(key)
   }else{
    return SecureStore.getItemAsync(key)
   }
}

export const AuthProvider = ({children}: any) => {
  const [authState, setAuthState] = useState<{
    email: string | null;
    authenticated: boolean | null;
    session : string | null;
  }>({
    email: null, authenticated: null, session: null
  });
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const loadSession = async () => {
      setIsLoading(true)


      const session = await getStorageItemAsync(SESSION_KEY)
      const email = await getStorageItemAsync(USER_KEY)

      if(session !== null && email !== null){
        console.log("applied session", session, email)
        setAuthState( (prev) => {
          return {
            email: email,
            authenticated: true,
            session: session,
          }
        })
      }

      setIsLoading(false)
    }
    loadSession()
  },[])


  const register = async (email: string, password: string) => {
    //registration Logic goes here
  }

  const login = async (email: string, password: string) => {
    setIsLoading(true)
  //login functionality goes here
    console.log("login called")

    setAuthState({
      email: email,
      authenticated: true,
      session: "super duper session token das wir vlt mal brauchen"
    })

    await setStorageItemAsync(SESSION_KEY, "super duper session token das wir vlt mal brauchen")
    await setStorageItemAsync(USER_KEY, email)
    setIsLoading(false)
  }

  const logout = async () => {
    setIsLoading(true)
    await setStorageItemAsync(SESSION_KEY, null)
    await setStorageItemAsync(USER_KEY, null)
    
    setAuthState({
      email: null,
      authenticated: false,
      session: null,
    });

    setIsLoading(false)
  };


  const value = {
    onRegister: register,
    onLogin: login,
    onLogout: logout,
    isLoading: isLoading,
    authState: authState
  }
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}