import { useEffect, useState } from "react";
import { Button, Form, Spinner, Table } from "react-bootstrap";
import { AddServer, getServerList, RemoveServer, type Server } from "../../../Lib/Servers";
import { useImmer } from "use-immer";
import styles from "../Management.module.scss";
import { BeginQuickConnect } from "../../../Lib/QuickConnect";


const ServerManagement = () => {
  const [servers, setServers] = useImmer<Array<Server> | undefined>(undefined);
  const [addCancelled, setAddCancelled] = useState(false);

  const [addServerInfo, setAddServerInfo] = useImmer({
    url: "",
    owner: "",
  });

  useEffect(() => {
    getServerList().then(serverList => {
      setServers(serverList);
    }).catch(err => {
      setServers([]);
      alert(err);
    })
  }, [setServers]);

  const onServerRemove = (url: string) => {
    RemoveServer(url).then(server => {
      setServers(draft => {
        const index = draft?.findIndex(s => s.url == server.url);

        if (index! > -1) {
          draft?.splice(index!, 1);
        }
      });
    }).catch(err => {
      alert(err);
    })
  }

  const onQuickConnect = () => {
    //start quick connect request
    //show quick connect code to user (modal)
    //poll quick connect state until it's authenticated
    //fetch quick connect credentials
    //onServerAdd(token);
    BeginQuickConnect(addServerInfo.url, onServerAdd, () => addCancelled).then(quickConnectCode => {
      //show modal with code
      alert(`Your quick connect code is ${quickConnectCode}`);
    }).catch(err => {
      //alert user to error
      //possibly clear fields?
      console.log(err);
      alert(err);
    });
  }

  const onServerAdd = (apiToken: string) => {
    //hide quick connect modal
    AddServer(addServerInfo.owner, addServerInfo.url, apiToken).then(result => {
      if (result.errored) {
        alert("Server was added, but is not working. Check the logs for details");
      }

      setServers(draft => {
        if (!draft) {
          draft = [result];
        }
        else {
          draft.push(result);
        }

        setAddServerInfo(draft => {
          draft.owner = "";
          draft.url = "";
        });
      })
    }).catch(err => {
      alert(err);
    })
  }

  return (
    <>
      <Form className={styles.form}>
        <h4>Add Server</h4>
        <Form.Group className="mb-3">
          <Form.Label>Owner</Form.Label>
          <Form.Control type="text" placeholder="Owner" onChange={e => setAddServerInfo(draft => { draft.owner = e.target.value })} value={addServerInfo.owner} />
        </Form.Group>
        <Form.Group className="mb-3">
          <Form.Label>Url</Form.Label>
          <Form.Control type="text" placeholder="Url" onChange={e => setAddServerInfo(draft => { draft.url = e.target.value })} value={addServerInfo.url} />
        </Form.Group>
        <Button className={styles.formButton} onClick={() => onQuickConnect()}>Quick Connect</Button>
      </Form>
      <Table className={styles.table} bordered striped>
        <thead>
          <tr>
            <th>Server Owner</th>
            <th>Server URL</th>
            <th>Server Status</th>
            <th>Remove</th>
          </tr>
        </thead>
        <tbody>
          {
            servers ?
              servers?.map(server => {
                return (
                  <tr key={server.url}>
                    <td>{server.owner}</td>
                    <td>{server.url}</td>
                    <td>{!server.errored ? "Online" : "Errored"}</td>
                    <td><Button variant="danger" onClick={() => onServerRemove(server.url)}>Remove</Button></td>
                  </tr>
                );
              })
              :
              <Spinner />
          }
        </tbody>
      </Table>
    </>
  )
}

export default ServerManagement;