import { faWifiExclamation } from "@fortawesome/pro-duotone-svg-icons"
import {
  faArrowLeft,
  faCheck,
  faSpinnerThird,
  faXmark,
} from "@fortawesome/pro-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import classNames from "classnames"
import { FormEvent, useState } from "react"

enum ProcessStates {
  "waiting",
  "loading",
  "success",
  "wrong",
  "error",
}
const messages: { [key in ProcessStates]: string } = {
  [ProcessStates.waiting]: "Enter Login Details",
  [ProcessStates.loading]: "Logging in...",
  [ProcessStates.success]: "Done!",
  [ProcessStates.wrong]: "Wrong username or password",
  [ProcessStates.error]: "An error occurred!",
}
const icons = {
  [ProcessStates.loading]: faSpinnerThird,
  [ProcessStates.success]: faCheck,
  [ProcessStates.wrong]: faXmark,
  [ProcessStates.error]: faWifiExclamation,
}
const iconClasses = {
  [ProcessStates.loading]: "animate-spin",
  [ProcessStates.success]: "text-green-500",
  [ProcessStates.wrong]: "text-red-500",
  [ProcessStates.error]: "animate-pulse text-amber-500 !text-8xl",
}

function Login() {
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")

  const [state, setState] = useState<ProcessStates>(ProcessStates.waiting)
  const [error, setError] = useState("")

  const elem = () => {
    if (state === ProcessStates.waiting)
      return (
        <form onSubmit={login}>
          <div className="mb-4 text-lg">
            <input
              className="rounded-3xl border-none bg-blue-400 bg-opacity-50 px-6 py-2 text-center text-inherit placeholder-slate-200 shadow-lg outline-none backdrop-blur-md"
              type="text"
              name="name"
              placeholder="Username or email"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
          </div>

          <div className="mb-4 text-lg">
            <input
              className="rounded-3xl border-none bg-blue-400 bg-opacity-50 px-6 py-2 text-center text-inherit placeholder-slate-200 shadow-lg outline-none backdrop-blur-md"
              type="Password"
              name="name"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>
          <div className="mt-8 flex justify-center text-lg text-black">
            <button
              type="submit"
              className="rounded-3xl bg-blue-400 bg-opacity-50 px-10 py-2 text-white shadow-xl backdrop-blur-md transition-colors duration-300 hover:bg-blue-600"
            >
              Login
            </button>
          </div>
        </form>
      )

    return (
      <>
        <div className="flex flex-col items-center rounded-3xl bg-slate-800/50 py-8 px-16 shadow-lg drop-shadow-md">
          <FontAwesomeIcon
            className={classNames("text-6xl", iconClasses[state])}
            icon={icons[state]}
          />
        </div>
        <div className="mt-8 flex justify-center text-lg text-black">
          <button
            type="button"
            className="rounded-3xl bg-blue-400 bg-opacity-50 px-10 py-2 text-white shadow-xl backdrop-blur-md transition-colors duration-300 hover:bg-blue-600"
            onClick={() => {
              setState(ProcessStates.waiting)
              setError("")
            }}
          >
            <FontAwesomeIcon className="-ml-4 mr-4" icon={faArrowLeft} />
            Return
          </button>
        </div>
      </>
    )
  }

  async function login(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setState(ProcessStates.loading)
    await fetch("/api/login", {
      method: "POST",
      body: JSON.stringify({ username, password }),
    })
      .then((res) => {
        if (res.status === 200) setState(ProcessStates.success)
        if (res.status === 401) setState(ProcessStates.wrong)
      })
      .catch((err: Error) => {
        setState(ProcessStates.error)
        setError(err.message)
      })
  }

  return (
    <div className="flex h-screen w-full items-center justify-center bg-gray-900 bg-[url('/images/wallpaper.jpg')] bg-cover bg-center bg-no-repeat">
      <div className="rounded-xl bg-gray-800 bg-opacity-50 px-16 py-10 shadow-lg backdrop-blur-md max-sm:px-8">
        <div className="text-white">
          <div className="mb-8 flex flex-col items-center">
            <img
              className="rounded-full shadow-lg"
              src="/logo512.png"
              width="150"
              alt="Avatar"
            />
            <h1 className="mb-2 text-2xl">Leaky Ships</h1>
            <span className="text-gray-300">
              {error ? error : messages[state]}
            </span>
          </div>
          {elem()}
        </div>
      </div>
    </div>
  )
}

export default Login
