import React, {useState, useEffect} from 'react';
import base64 from 'base-64';
import { Modal, Button, Group, TextInput, Loader } from '@mantine/core';
import { useDebouncedValue } from '@mantine/hooks';

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

// const discoverBackend = async () => {
//   const serverSettings = await fetch("http://localhost:3500/config")
//   console.log("ServerSettings: ", serverSettings.json())
// }



function App() {
  const [serverConfig, setServerConfig] = useState({})
  const [serverPort, setServerPort] = useState('3501')
  const [portModalOpen, setPortModalOpen] = useState(false)
  const [authModalOpen, setAuthModalOpen] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  const [fullServerPort] = useDebouncedValue(serverPort, 200)
  //headers.append("Authorization", "Basic " + base64.encode("user:password"));
  const user = "admin"
  const password = "password"

  useEffect(() => {
    setPortModalOpen(false)
    fetch(`http://localhost:${fullServerPort}/config`)
      .then(response => {
        if (!response.ok) {
          console.log("Server not responding as expected, this should not happen!")
        } else {
          response.json().then(data => {
            setServerConfig(data)
            setPortModalOpen(false)
            setIsLoading(false)
          })
        }
      }).catch(err => {
        console.log("Port value is incorrect, please change! ", err)
        setPortModalOpen(true)
      })

  }, [fullServerPort])

  useEffect(() => {
    console.log("Loading Server Config: ", serverConfig)
    if (serverConfig["BasicAuth"]) {
      setAuthModalOpen(true)
    }
  }, [serverConfig])

  return (
    <>
     <Modal
        opened={portModalOpen}
        onClose={() => setPortModalOpen(false)}
        title="Communication Failed, server port may not be what was expected!"
      >
        <TextInput label="Server Port" value={serverPort} onChange={(e) => setServerPort(e.currentTarget.value)} required></TextInput>
      </Modal>
      <Modal
        opened={authModalOpen}
        onClose={() => setAuthModalOpen(false)}
        title="Please Login!"
      >
        <TextInput label="UserName" value={serverPort} onChange={(e) => setServerPort(e.currentTarget.value)} required></TextInput>
      </Modal>
    {isLoading ? <Group position="center"><Loader size="xl"></Loader></Group> : <div>Welcome to goInventorize!</div>}
    </>
  );
}

export default App;
