import { Loader2 } from "lucide-react"
import { useState } from "react"
import { useNavigate } from "react-router-dom"
import { toast } from "sonner"

import { resolveAuthMobile, startGoogleLogin } from "../../api/users"
import { Button } from "../../components/ui/button"
import { Input } from "../../components/ui/input"
import { useAuthFlow } from "../../context/AuthFlowContext"
import { useTranslation } from "../../hooks/useTranslation"
import { AuthPanel } from "./AuthPanel"
import { getApiErrorMessage } from "./utils"

const GoogleIcon = () => (
  <svg aria-hidden="true" className="h-5 w-5" viewBox="0 0 24 24">
    <path
      d="M21.805 10.023h-9.72v3.955h5.57c-.24 1.272-.96 2.35-2.042 3.07v2.548h3.3c1.933-1.78 3.042-4.4 3.042-7.506 0-.692-.062-1.357-.15-2.067Z"
      fill="#4285F4"
    />
    <path
      d="M12.085 22c2.79 0 5.13-.925 6.84-2.504l-3.3-2.548c-.924.617-2.103.986-3.54.986-2.705 0-4.99-1.823-5.807-4.28H2.87v2.626A10.33 10.33 0 0 0 12.085 22Z"
      fill="#34A853"
    />
    <path
      d="M6.278 13.654A6.214 6.214 0 0 1 5.95 11.7c0-.68.117-1.34.328-1.954V7.12H2.87A10.31 10.31 0 0 0 1.75 11.7c0 1.65.39 3.218 1.12 4.58l3.408-2.626Z"
      fill="#FBBC05"
    />
    <path
      d="M12.085 5.466c1.52 0 2.882.522 3.955 1.55l2.966-2.966C17.21 2.387 14.874 1.4 12.085 1.4A10.33 10.33 0 0 0 2.87 7.12l3.408 2.626c.818-2.457 3.103-4.28 5.807-4.28Z"
      fill="#EA4335"
    />
  </svg>
)

export function LoginMobilePage() {
  const navigate = useNavigate()
  const { t } = useTranslation()
  const { state, setMobile, clearOtpDelivery, clearSignupDetails, resetFlow } = useAuthFlow()
  const [loading, setLoading] = useState(false)

  const handleContinue = async () => {
    if (!state.login.mobile) {
      toast.error(t.login.toasts.enterMobile)
      return
    }

    setLoading(true)
    try {
      const result = await resolveAuthMobile(state.login.mobile)
      resetFlow("forgotPassword")

      if (result.status === "existing_user") {
        clearOtpDelivery("login")
        navigate("/auth/login/password")
        return
      }

      resetFlow("signup")
      clearSignupDetails()
      setMobile("signup", state.login.mobile)
      navigate("/auth/signup/password")
    } catch (error) {
      toast.error(getApiErrorMessage(error, t.login.toasts.resolveMobileFailed))
    } finally {
      setLoading(false)
    }
  }

  return (
    <AuthPanel
      title={t.login.loginTitle}
      description={t.login.loginDescription}
      step={{ current: 1, total: 3, label: t.login.stepLabel(1, 3) }}
    >
      <form
        onSubmit={(event) => {
          event.preventDefault()
          void handleContinue()
        }}
        className="grid gap-4"
      >
        <Input
          id="login-mobile"
          placeholder={t.login.mobilePlaceholder}
          type="tel"
          dir="ltr"
          maxLength={11}
          value={state.login.mobile}
          onChange={(event) => setMobile("login", event.target.value)}
          className="h-11 text-start"
        />

        <Button
          type="submit"
          disabled={loading}
          className="h-11 w-full"
        >
          {loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
          {t.login.continue}
        </Button>

        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <span className="w-full border-t border-slate-200 dark:border-slate-800" />
          </div>
          <div className="relative flex justify-center text-xs uppercase">
            <span className="bg-white px-2 text-slate-500 transition-colors dark:bg-slate-950 dark:text-slate-400">
              {t.login.orContinueWith}
            </span>
          </div>
        </div>

        <Button
          type="button"
          variant="outline"
          disabled={loading}
          onClick={startGoogleLogin}
          className="h-11 w-full"
        >
          <GoogleIcon />
          <span className="ms-3">{t.login.continueWithGoogle}</span>
        </Button>

      </form>
    </AuthPanel>
  )
}
