import React, {useState, useEffect, useContext, createContext} from 'react';
import base64 from 'base-64';
import Home from './components/pages/Home'
import { Modal, Button, Text, Group, TextInput, Loader } from '@mantine/core';
import { useDebouncedValue, useLocalStorageValue } from '@mantine/hooks';

import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom'



const defaultSettings = {"serverURL": window.location.href.slice(0, -1), "Timezone": "America/Detroit"}


const APIContext = createContext();

function App() {
  const [portModalOpen, setPortModalOpen] = useState(false)
  const [authModalOpen, setAuthModalOpen] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  // json.stringify({"serverURL": window.location.href.slice(0, -1), "Timezone": "America/Detroit"})
  const [serverConfigLS, setServerConfigLS] = useLocalStorageValue({key: 'serverConfig', defaultValue: JSON.stringify(defaultSettings)})
  const [serverConfig, setServerConfig] = useState(defaultSettings)

  const [fullServerURL] = useDebouncedValue(serverConfig["serverURL"], 800);

  //headers.append("Authorization", "Basic " + base64.encode("user:password"));
  const user = "admin"
  const password = "password"

  useEffect(() => {
    console.log("Checking local storage for server settings: ", JSON.parse(serverConfigLS))
    if(JSON.parse(serverConfigLS)) {
      setServerConfig(JSON.parse(serverConfigLS))
    }
  }, [serverConfigLS, setServerConfig])


  useEffect(() => {
    setPortModalOpen(false)
    const lastChar = fullServerURL[fullServerURL.length - 1]
    let newURL = fullServerURL
    if (lastChar === "/") {
      newURL = fullServerURL.slice(0, -1)
    }
    console.log("Auto-discover URL attempted: ", `${newURL}/config`)
    fetch(`${newURL}/config`)
      .then(response => {
        console.log("RESPONSE: ", response)
        if (!response.ok) {
          console.log("Server not responding as expected, this should not happen!")
          setPortModalOpen(true)
        } else {
          response.json().then(data => {
            console.log("Connected to Server! ", data)
            setServerConfig({...serverConfig, "Timezone": data["Timezone"], "BasicAuth": data["BasicAuth"]})
            setServerConfigLS(JSON.stringify({...serverConfig, "Timezone": data["Timezone"], "BasicAuth": data["BasicAuth"]}))
            setPortModalOpen(false)
            setIsLoading(false)
          }).catch(err => {
            console.log("Server URL is incorrect, please change! ", err)
            setPortModalOpen(true)
          })
        }
      }).catch(err => {
        console.log("Server URL is incorrect, please change! ", err)
        setPortModalOpen(true)
      })

  }, [fullServerURL])

  useEffect(() => {
    console.log("Loading Server Config: ", serverConfig)
    if (serverConfig["BasicAuth"]) {
      console.log("Looks like auth is required!")
      //setAuthModalOpen(true)
    }
  }, [serverConfig])

  return (
    <APIContext.Provider value={{...serverConfig}}>
     <Modal
        opened={portModalOpen}
        onClose={() => setPortModalOpen(false)}
        title="Communication Failed, server URL may not be what was expected!"
      >
        <Text>Guessed Server URL: {serverConfig["serverURL"]} does not appear to be correct, please enter correct url.</Text>
        <TextInput label="Server URL" value={serverConfig["serverURL"]} onChange={(e) => setServerConfig({...serverConfig, "serverURL": e.currentTarget.value})} required></TextInput>
      </Modal>
      <Modal
        opened={authModalOpen}
        onClose={() => setAuthModalOpen(false)}
        title="Please Login!"
      >
        <TextInput label="UserName" value={serverConfig["serverURL"]} onChange={(e) => setServerConfig({"ServerURL": e.currentTarget.value})} required></TextInput>
        <TextInput label="UserName" type="password" value={serverConfig["serverURL"]} onChange={(e) => setServerConfig({"ServerURL": e.currentTarget.value})} required></TextInput>
      </Modal>
      {isLoading ? <Group position="center"><Loader size="xl"></Loader></Group> : <div>Welcome to goInventorize!</div>}
    <Router>
      <Switch path="/">
        <Home />
      
      </Switch>
    </Router>
    
    
    </APIContext.Provider>
    
  );
}

export default App;
