import type { ClientToServerEvents, ServerToClientEvents } from "../api/ws"
import getAccessToken from "@lib/frontend/getAccessToken"
import { ChangeEventHandler, useEffect, useState } from "react"
import { io, Socket } from "socket.io-client"

let socket: Socket<ServerToClientEvents, ClientToServerEvents>

const Home = () => {
  const [input, setInput] = useState("")
  const [data, setData] = useState("")

  useEffect(() => {
    socketInitializer()
  }, [])

  async function socketInitializer() {
    await fetch("/api/ws")
    socket = io()
    await fetch("/api/login", {
      method: "POST",
      body: JSON.stringify({ username: "warst", password: "warst" }),
    })
    getAccessToken().then((token) => {
      socket.emit("authenticate", { token })
    })

    socket.on("connect", () => {
      console.log("connected")
    })

    socket.on("authenticated", () => {
      console.log("Yay!")
    })

    socket.on("unauthenticated", () => {
      console.log("No... pls work")
    })

    socket.on("update-input", (msg) => {
      setData(msg)
    })
  }

  const onChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
    setInput(e.target.value)
    socket.emit("input-change", e.target.value)
  }

  return (
    <>
      <input
        placeholder="Type something"
        value={input}
        onChange={onChangeHandler}
        onDoubleClick={() => setInput(data)}
      />
      <h1>{data}</h1>
    </>
  )
}

export default Home
