import React, {useState, useEffect, useContext, createContext} from 'react';
import base64 from 'base-64';
import HomePage from './components/pages/HomePage';
import Locations from './components/pages/Locations'
import { Modal, Button, Text, Group, TextInput, Loader, AppShell } from '@mantine/core';
import {BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom'
import { useDebouncedValue, useLocalStorageValue } from '@mantine/hooks';


import SideBar from './components/SideBar';
import AppHeader from './components/AppHeader';


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


const APIContext = createContext();

function App() {
  // Main nav/sidebar appshell openend
  const [shellOpened, setShellOpened] = useState(false)
  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}}>
      <Router>
        <AppShell
            navbarOffsetBreakpoint="sm" // navbarOffsetBreakpoint controls when navbar should no longer be offset with padding-left
            fixed       // fixed prop on AppShell will be automatically added to Header and Navbar
            navbar={<SideBar opened={shellOpened}/>}
            header={<AppHeader opened={shellOpened} setOpened={setShellOpened}/>}
          >
            <Routes>
              <Route path="/" element={<HomePage />} />
              <Route path="/locations" element={<Locations />} />
            </Routes>
        </AppShell>
      </Router>
     <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>}
   


    </APIContext.Provider>
    
  );
}

export default App;
