import { useRouter } from "expo-router";
import { useState, useEffect } from "react";
import * as WebBrowser from "expo-web-browser";
import { Platform } from "react-native";

import { AuthLayout } from "@/components/auth/AuthLayout";
import { AuthHeader } from "@/components/auth/AuthHeader";
import { AuthCard } from "@/components/auth/AuthCard";
import { SignInForm } from "@/components/auth/SignInForm";
import { ForgotPasswordLink } from "@/components/auth/ForgotPasswordLink";
import { useAuthContext } from "@/auth/AuthContext";

WebBrowser.maybeCompleteAuthSession();

const useWarmUpBrowser = () => {
  useEffect(() => {
    if (Platform.OS !== "web") {
      WebBrowser.warmUpAsync();
      return () => {
        WebBrowser.coolDownAsync();
      };
    }
  }, []);
};

const SignIn = () => {
  const router = useRouter();
  const { login, isAuthenticated, loading } = useAuthContext();

  useWarmUpBrowser();

  const [errorMessage, setErrorMessage] = useState("");
  const successMessage = "";
  const isResettingPassword = false;

  const onForgotPasswordPress = async () => {
    router.push("/forgot-password");
  };

  const onSignInSubmit = async (vals: {
    emailAddress: string;
    password: string;
  }) => {
    setErrorMessage("");
    try {
      await login(vals.emailAddress, vals.password);
      router.replace("/");
    } catch (err: any) {
      const msg = err?.message || "Invalid credentials";
      setErrorMessage(msg);
    }
  };

  useEffect(() => {
    if (!loading && isAuthenticated) {
      router.replace("/");
    }
  }, [loading, isAuthenticated, router]);

  return (
    <AuthLayout>
      <AuthHeader title="Bird Eye View" />

      <AuthCard title="Welcome Back" subtitle="Sign in to continue">
        <SignInForm
          errorMessage={errorMessage}
          successMessage={successMessage}
          isLoading={loading}
          onSignInSubmit={onSignInSubmit}
        />

        <ForgotPasswordLink
          onPress={onForgotPasswordPress}
          isResetting={isResettingPassword}
          disabled={isResettingPassword || loading}
        />
      </AuthCard>
    </AuthLayout>
  );
};

export default SignIn;
