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 [isLoading, setIsLoading] = useState(false);
  const successMessage = "";
  const isResettingPassword = false;

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

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

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

  return (
    <AuthLayout>
      <AuthHeader title="Project Athena" />

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

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

export default SignIn;
