import { useState } from "react"
import { BREATHECODE_HOST } from "../utils/constants"
import { SVGS } from "../assets/svgs"
import toast from "react-hot-toast"
import useStore from "../utils/store"
import { useShallow } from "zustand/react/shallow"
import { login4Geeks } from "../utils/lib"

export default function Login({ onFinish }: { onFinish: () => void }) {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [showForm, setShowForm] = useState(false)
  const planToRedirect = useStore((state) => state.planToRedirect)

  const { setAuth } = useStore(
    useShallow((state) => ({ setAuth: state.setAuth }))
  )

  const login = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    const tid = toast.loading("Logging in…")

    if (!email || !password) {
      setIsLoading(false)
      toast.error("Please fill all fields", { id: tid })
      return
    }

    const resp = await login4Geeks({ email, password })
    if (!resp) {
      setIsLoading(false)
      toast.error("Invalid credentials", { id: tid })
      return
    }

    toast.success("Logged in successfully", { id: tid })
    setAuth({
      bcToken: resp.token,
      userId: resp.user.id,
      rigoToken: resp.rigobot.key,
      user: resp.user,
    })
    setIsLoading(false)
    onFinish()
  }

  function stringToBase64(str: string) {
    return btoa(unescape(encodeURIComponent(str)))
  }

  function getCurrentUrlWithQueryParams() {
    return window.location.href
  }

  const redirectGithub = () => {
    const url = stringToBase64(getCurrentUrlWithQueryParams())
    window.location.href = `${BREATHECODE_HOST}/v1/auth/github/?url=${url}`
  }

  const redirectGoogle = () => {
    const url = stringToBase64(getCurrentUrlWithQueryParams())
    window.location.href = `${BREATHECODE_HOST}/v1/auth/google?url=${url}`
  }

  return (
    <div
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-1000"
      onClick={onFinish}
    >
      <div
        className="bg-white p-8 rounded-xl shadow-md max-w-sm w-full"
        onClick={(e) => e.stopPropagation()}
      >
        <p className="mb-4 text-center text-gray-700">
          You need to have a 4Geeks account with a creator plan to create a
          tutorial.
        </p>
        <button
          onClick={redirectGithub}
          className="w-full border border-gray-300 py-2 rounded-md font-semibold flex items-center justify-center gap-2 mb-4 cursor-pointer"
        >
          {SVGS.github} LOGIN WITH GITHUB
        </button>
        <button
          onClick={redirectGoogle}
          className="w-full border border-gray-300 py-2 rounded-md font-semibold flex items-center justify-center gap-2 mb-4 cursor-pointer"
        >
          {SVGS.google} LOGIN WITH GOOGLE
        </button>

        <div className="flex items-center mb-4">
          <hr className="flex-grow border-gray-300" />
          <span className="mx-2 text-gray-400 text-sm">or</span>
          <hr className="flex-grow border-gray-300" />
        </div>

        {showForm ? (
          <form className="space-y-3" onSubmit={login}>
            <input
              type="email"
              placeholder="Email"
              className="w-full border border-gray-300 px-3 py-2 rounded-md"
              onChange={(e) => setEmail(e.target.value)}
            />
            <input
              type="password"
              placeholder="Password"
              className="w-full border border-gray-300 px-3 py-2 rounded-md"
              onChange={(e) => setPassword(e.target.value)}
            />
            <div className="flex gap-2 mt-4">
              <button
                type="submit"
                className="flex-1 bg-sky-500 text-white py-2 rounded-md font-semibold cursor-pointer"
              >
                {isLoading ? "Logging in..." : "Log in"}
              </button>
              <button
                type="button"
                onClick={() => setShowForm(false)}
                className="flex-1 border border-sky-500 text-sky-600 py-2 rounded-md font-semibold cursor-pointer"
              >
                Skip
              </button>
            </div>
            <div className="text-sm text-gray-600 mt-2">
              Forgot your password?{" "}
              <a
                href={`${BREATHECODE_HOST}/v1/auth/password/reset?url=${getCurrentUrlWithQueryParams()}`}
                className="text-sky-600 font-medium"
              >
                Recover it here.
              </a>
            </div>
          </form>
        ) : (
          <button
            onClick={() => setShowForm(true)}
            className="w-full bg-blue-600 text-white py-2 rounded-md font-semibold cursor-pointer"
          >
            Login with Email
          </button>
        )}

        <div className="flex justify-between items-center mt-4">
          <div className="bg-blue-50 text-sm p-2 rounded text-left">
            <p className="text-gray-700 m-0">You don't have an account?</p>
            <a
              href={`https://4geeks.com/checkout?plan=${planToRedirect}`}
              target="_blank"
              className="text-blue-600 font-medium"
            >
              Register here.
            </a>
          </div>
        </div>
      </div>
    </div>
  )
}
