import { faLeftLong } from "@fortawesome/pro-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { signIn, useSession } from "next-auth/react"
import { useRouter } from "next/router"
import { useEffect, useState } from "react"
import { toast } from "react-toastify"

type SignInErrorTypes =
  | "Signin"
  | "OAuthSignin"
  | "OAuthCallback"
  | "OAuthCreateAccount"
  | "EmailCreateAccount"
  | "Callback"
  | "OAuthAccountNotLinked"
  | "EmailSignin"
  | "CredentialsSignin"
  | "SessionRequired"
  | "default"

const errors: Record<SignInErrorTypes, string> = {
  Signin: "Try signing in with a different account.",
  OAuthSignin: "Try signing in with a different account.",
  OAuthCallback: "Try signing in with a different account.",
  OAuthCreateAccount: "Try signing in with a different account.",
  EmailCreateAccount: "Try signing in with a different account.",
  Callback: "Try signing in with a different account.",
  OAuthAccountNotLinked:
    "To confirm your identity, sign in with the same account you used originally.",
  EmailSignin: "The e-mail could not be sent.",
  CredentialsSignin:
    "Sign in failed. Check the details you provided are correct.",
  SessionRequired: "Please sign in to access this page.",
  default: "Unable to sign in.",
}

function Login() {
  const [email, setEmail] = useState("")
  const { status } = useSession()
  const router = useRouter()

  const errorType = router.query.error as SignInErrorTypes

  useEffect(() => {
    if (!errorType) return
    toast.error(errors[errorType] ?? errors.default, { theme: "colored" })
  }, [errorType])

  useEffect(() => {
    if (status === "authenticated") router.push("/")
  }, [router, status])

  function login(provider: "email" | "azure-ad") {
    return () => {
      signIn(provider, { email, callbackUrl: "/" })
    }
  }

  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-60 px-16 py-10 text-white shadow-lg backdrop-blur-md max-sm:px-8">
        <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">Choose Login Method</span>
        </div>
        {errorType && <hr className="mb-8 border-gray-400" />}
        <div className="flex flex-col">
          <div className="flex flex-col">
            <label htmlFor="email" className="mx-2 text-lg">
              Email
            </label>
            <input
              className="my-1 rounded-lg border-2 border-gray-500 bg-slate-800 bg-opacity-60 px-6 py-2 text-center text-inherit placeholder-slate-400 shadow-lg outline-none backdrop-blur-md focus-within:border-blue-500"
              type="text"
              name="email"
              placeholder="user@example.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <button
              id="email"
              onClick={login("email")}
              className="my-1 rounded-lg bg-blue-500 bg-opacity-75 px-10 py-3 text-white shadow-inner drop-shadow-md backdrop-blur-md transition-colors duration-300 hover:bg-blue-600"
            >
              Sign in with Email
            </button>
          </div>

          <div className="flex flex-row items-center">
            <hr className="w-full" />
            <span className="mx-4 my-2">or</span>
            <hr className="w-full" />
          </div>

          <div className="my-2 flex flex-col rounded-lg bg-gradient-to-tr from-[#fff8] via-[#fffd] to-[#fff8] p-4 shadow-lg drop-shadow-md">
            <a
              href="https://gbs-grafschaft.de/"
              target="_blank"
              rel="noreferrer"
            >
              <img
                src="/images/logo-gbs.png"
                loading="lazy"
                alt="Gewerbliche Berufsbildende Schulen"
                className="m-4 mt-2 w-60 justify-center"
              />
            </a>
            <button
              id="microsoft"
              onClick={login("azure-ad")}
              className="flex w-full justify-evenly rounded-lg border border-gray-400 bg-slate-100 px-5 py-3 text-black drop-shadow-md duration-300 hover:bg-slate-200"
            >
              <img
                src="/images/Microsoft_icon.svg"
                loading="lazy"
                height="24"
                width="24"
                alt="Microsoft_icon"
              />
              <span>Sign in with Microsoft</span>
            </button>
          </div>
        </div>
        {errorType && <hr className="mt-8 border-gray-400" />}
        {errorType && (
          <div className="flex flex-col items-center">
            <button
              id="back"
              onClick={() => router.push("/")}
              className="mt-10 rounded-lg border-2 border-gray-400 bg-gray-500 bg-opacity-75 px-16 py-2 text-white shadow-inner drop-shadow-md backdrop-blur-md transition-colors duration-300 hover:border-blue-600"
            >
              <FontAwesomeIcon icon={faLeftLong} />
              <span className="mx-4 font-bold">Return</span>
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

export default Login
