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, registerUserWithFormData } from "../utils/lib"
import { useTranslation } from "react-i18next"

export default function Login({ onFinish }: { onFinish: () => void }) {
  // Login states
  const { t } = useTranslation()

  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [showForm, setShowForm] = useState(false)
  // Signup states
  const [showSignup, setShowSignup] = useState(false)
  const [signupData, setSignupData] = useState({
    firstName: "",
    lastName: "",
    email: "",
  })
  // const planToRedirect = useStore((state) => state.planToRedirect)
  const { setAuth } = useStore(
    useShallow((state) => ({ setAuth: state.setAuth }))
  )

  // Login handler
  const login = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setIsLoading(true)
    const tid = toast.loading(t("login.loggingIn"))
    try {
      if (!email || !password) {
        setIsLoading(false)
        toast.error(t("login.pleaseFillAllFields"), { id: tid })
        return
      }
      const resp = await login4Geeks({ email, password })
      if (!resp) {
        setIsLoading(false)
        toast.error(t("login.invalidCredentials"), { id: tid })
        return
      }
      toast.success(t("login.loggedInSuccessfully"), { id: tid })
      setAuth({
        bcToken: resp.token,
        userId: resp.user.id,
        rigoToken: resp.rigobot.key,
        user: resp.user,
        publicToken: "",
      })
      setIsLoading(false)
      onFinish()
    } catch (error) {
      console.error(error)
      toast.error("Invalid credentials", { id: tid })
      setIsLoading(false)
    }
  }

  // Signup handler
  const handleSignup = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setIsLoading(true)
    const tid = toast.loading(t("login.creatingAccount"))
    const { firstName, lastName, email } = signupData
    if (!firstName || !lastName || !email) {
      setIsLoading(false)
      toast.error(t("login.pleaseFillAllFields"), { id: tid })
      return
    }
    try {
      await registerUserWithFormData(firstName, lastName, email)
      toast.success(t("login.accountCreated"), { id: tid })
      setShowSignup(false)
      setShowForm(true)
      setEmail(email)
    } catch (err) {
      toast.error(t("login.registrationFailed"), { id: tid })
    } finally {
      setIsLoading(false)
    }
  }

  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()}
      >
        {showSignup ? (
          <>
            <h2 className="mb-4 text-xl font-semibold text-center">
              {t("login.createYourAccount")}
            </h2>
            <form className="space-y-3" onSubmit={handleSignup}>
              <input
                type="text"
                placeholder={t("login.firstName")}
                className="w-full border border-gray-300 px-3 py-2 rounded-md"
                value={signupData.firstName}
                onChange={(e) =>
                  setSignupData({ ...signupData, firstName: e.target.value })
                }
              />
              <input
                type="text"
                placeholder={t("login.lastName")}
                className="w-full border border-gray-300 px-3 py-2 rounded-md"
                value={signupData.lastName}
                onChange={(e) =>
                  setSignupData({ ...signupData, lastName: e.target.value })
                }
              />
              <input
                type="email"
                placeholder="Email"
                className="w-full border border-gray-300 px-3 py-2 rounded-md"
                value={signupData.email}
                onChange={(e) =>
                  setSignupData({ ...signupData, email: e.target.value })
                }
              />
              <button
                type="submit"
                className="w-full bg-blue-600 text-white py-2 rounded-md font-semibold cursor-pointer"
                disabled={isLoading}
              >
                {isLoading ? t("login.creating") : t("login.signUp")}
              </button>
            </form>
            <div className="mt-4 text-sm text-center">
              {t("login.alreadyHaveAnAccount")}
              <button
                className="text-blue-600 font-medium"
                onClick={() => {
                  setShowSignup(false)
                  setShowForm(true)
                }}
              >
                {t("login.logInHere")}
              </button>
            </div>
          </>
        ) : (
          <>
            <p className="mb-4 text-center text-gray-700">
              {t("login.youNeedToHaveAnAccount")}
            </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} {t("login.loginWithGithub")}
            </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} {t("login.loginWithGoogle")}
            </button>
            <div className="flex items-center mb-4">
              <hr className="flex-grow border-gray-300" />
              <span className="mx-2 text-gray-400 text-sm">
                {t("login.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"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
                <input
                  type="password"
                  placeholder={t("login.password")}
                  className="w-full border border-gray-300 px-3 py-2 rounded-md"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <div className="flex gap-2 mt-4">
                  <button
                    type="submit"
                    className="flex-1 bg-blue-500 text-white py-2 rounded-md font-semibold cursor-pointer"
                  >
                    {isLoading ? t("login.loggingIn") : t("login.logIn")}
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowForm(false)}
                    className="flex-1 border border-blue-500 text-blue-600 py-2 rounded-md font-semibold cursor-pointer"
                  >
                    {t("login.skip")}
                  </button>
                </div>
                <div className="text-sm text-gray-600 mt-2">
                  {t("login.forgotPassword")}
                  <a
                    href={`${BREATHECODE_HOST}/v1/auth/password/reset?url=${getCurrentUrlWithQueryParams()}`}
                    className="text-blue-600 font-medium"
                  >
                    {t("login.recoverItHere")}
                  </a>
                </div>
              </form>
            ) : (
              <button
                onClick={() => setShowForm(true)}
                className="w-full bg-blue-600 text-white py-2 rounded-md font-semibold cursor-pointer"
              >
                {t("login.loginWithEmail")}
              </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">
                  {t("login.youDontHaveAnAccount")}
                </p>
                <a
                  href={`https://learn.learnpack.co/signup?callback=${encodeURIComponent(window.location.href)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-blue-600 font-medium"
                >
                  {t("login.registerHere")}
                </a>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  )
}
