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};
  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;
    isLoading: boolean;
  }>({
    email: null, authenticated: null, session: null, isLoading: false
  });

  useEffect(() => {
    const loadSession = async () => {
      setAuthState((prev) => {
        return {
          ...prev,
          isLoading: true
        }
      })


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

      if(session && email){
        setAuthState({
          email: email,
          authenticated: true,
          session: session,
          isLoading: false
        })
      }
      setAuthState((prev) => {
        return {
          ...prev,
          isLoading: false
        }
      })
    }
    loadSession()
  },[])


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

  const login = async (email: string, password: string) => {

  //login functionality goes here
    console.log("login called")
    setAuthState((prev) => {
      return{
        ...prev,
        isLoading: true
      }
    })

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

    })

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

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


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