import { useRouter } from 'expo-router';
import React, { createContext, useContext, useState } from 'react';
import { Alert, Platform } from 'react-native';
import * as SecureStore from "expo-secure-store"
import * as crypto from "expo-crypto"
import {showToast} from "./../components/toastwrapper"









// Create Context for Auth State
export const AuthContext = createContext();


export const register = async (email,username,password, pubKey) => {
  const apiurl = "http://localhost:4000/register"
  const requestData = {
    email,username,password,pubKey
  }
  try{
    const response = await fetch(apiurl, {
      method:"POST",
      headers: {
        "Content-Type": "application/json", // Specify JSON format
      },
      body: JSON.stringify(requestData)
    })
    if (!response.ok) {
      const errorData = await response.text()
      if (errorData === "User already exists") {
        showToast('error', 'Sign-up Failed', 'Username taken')
      } 
      console.log(errorData)
      return false
    } else if (response.ok){      
      return true
    }
  }catch (err){
    console.log(err)
    
  }
}

export const realLogin = async (username,password) => {
  const apiurl = "http://localhost:4000/login"
  const requestData = {
    username,password
  }
  try{
    const response = await fetch(apiurl, {
      method:"POST",
      headers: {
        "Content-Type": "application/json", // Specify JSON format
      },
      body: JSON.stringify(requestData)
    })
    if (!response.ok) {
      const errorData = await response.text()
      console.log(errorData)
      return false
    } else if (response.ok){
      console.log("Logged In")
      const resData = await response.json()
      console.log("ServerKey",resData.serverPubKey)
      if (Platform.OS ==="web") {
        localStorage.setItem("username", username)
        localStorage.setItem("jwtToken", resData.token)
        localStorage.setItem("serverPubKey", resData.serverPubKey)
      } else {
        await SecureStore.setItemAsync("jwtToken",resData.token)
      }
      
      
      return true
    }
  }catch (err){
    console.log(err)
  }
}

// Custom Hook to use AuthContext
export const useAuth = () => useContext(AuthContext);

// AuthProvider to provide AuthContext to the app
export const AuthProvider = ({ children }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);  // Default: Not logged in
  const [jsontoken, setjsontoken] = useState("")
  
  
  
  const login = () => setIsLoggedIn(true); // Set user as logged in
  const logout = () => setIsLoggedIn(false);  // Set user as logged out

  return (
    <AuthContext.Provider value={{ isLoggedIn,jsontoken, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};