import { useEffect, useState } from "react";
import ConnectForm from "./pages/Login";
import { Client } from "paho-mqtt";
import UnauthPage from "./layout/UnauthPage";
import { Spin } from "antd";
import Page from "./layout/Page";
import Spectrum from "./pages/Spectrum";

const App = () => {
  const [client, setClient] = useState(null);
  const [connected, setConnected] = useState(false);
  const [connecting, setConnecting] = useState(false);
  const [alert, setAlert] = useState(null);

  const onConnect = (url, options) => {
    console.log(`Trying to connect to ${url}...`);

    const _client = new Client(url, options.clientId);

    _client.onConnectionLost = onDisconnect;

    _client.connect({
      onSuccess: onConnected,
      onFailure: onError,
      userName: options.username,
      password: options.password,
      cleanSession: options.clean,
      timeout: options.connectTimeout,
    });

    console.log('Options:', options);

    setClient(_client);
    setConnecting(true);
  };

  const onConnected = () => {
    console.log("Connected!");
    setConnecting(false);
    setConnected(true);
  };

  const onError = (err) => {
    console.error("Failed to connect", err);
    setConnecting(false);
    setAlert({ type: 'error', msg: `Could not connect, error: ${err.errorMessage}` });
  };

  const onDisconnect = () => {
    client.disconnect();
  };

  useEffect(() => {
    if (connecting)
      setAlert(null);
  }, [connecting]);

  if (!connected)
    return (
      <UnauthPage content={
        <ConnectForm
          connect={onConnect}
          btnContent={connecting ? <Spin /> : 'Connect'}
        />
      } alert={alert} />
    )

  return (
    <Page
      content={<Spectrum />} />
  )
}

export default App