import { useState, useEffect } from "react";
import mqtt from "mqtt";
import { TextSection } from "@components/index";
import styled from "styled-components";

const CoffeeTitle = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 3rem;
  font-weight: bold;
`;

const Cups = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 7rem;
  font-variant-numeric: tabular-nums;
`;

const Time = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
`;

const GuildroomView = () => {
  const [brewing, setBrewing] = useState<boolean>(false);
  const [time, setTime] = useState<number>(0);
  const [cups, setCups] = useState<number>(0);
  const [client, setClient] = useState<mqtt.MqttClient | null>(null);
  const [status, setStatus] = useState<boolean>(false);

  useEffect(() => {
    setStatus(false);
    if (process.env.NEXT_PUBLIC_MQTT_HOST) {
      setClient(mqtt.connect(`ws://${process.env.NEXT_PUBLIC_MQTT_HOST}`));
    }
  }, []);

  useEffect(() => {
    if (client) {
      client.on("connect", () => {
        setStatus(true);
        client.subscribe("sik/kiltahuone/kahvivaaka/#", (err) => {
          if (!err) {
            console.log("Connected to MQTT server!");
          }
        });
      });
      client.on("error", (err) => {
        console.error("Connection error: ", err);
        client.end();
      });
      client.on("reconnect", () => {
        setStatus(false);
      });
      client.on("offline", () => {
        setStatus(false);
      });
      client.on("message", (topic, message) => {
        if (topic === "sik/kiltahuone/kahvivaaka/cups") {
          setCups(Number(message.toString()));
        }
        if (topic === "sik/kiltahuone/kahvivaaka/brewtime") {
          setTime(Number(message.toString()));
        }
        if (topic === "sik/kiltahuone/kahvivaaka/brewing") {
          setBrewing(Boolean(message.toString()));
        }
      });
    }
  }, [client]);

  if (!status) {
    return (
      <CoffeeTitle style={{ margin: "10%" }}>NO MQTT CONNECTION</CoffeeTitle>
    );
  }

  return (
    <div style={{ margin: "10%" }}>
      <CoffeeTitle>{brewing ? "Brewing more..." : "Cups left"}</CoffeeTitle>
      <Cups>{cups}</Cups>
      <Time>Brewed {time} min ago</Time>
    </div>
  );
};

export default GuildroomView;
