import useAuthContext from "@/components/providers/auth-provider/hook";
import { Button, ButtonText } from "@/components/ui/button";
import Content from "@/components/ui/content";
import { Divider } from "@/components/ui/divider";
import LoginForm, { LoginFormData } from "@/components/ui/login-form";
import Panel from "@/components/ui/panel";
import { ThemedText } from "@/components/ui/themed-text";
import getErrorAxiosMessage from "@/utils/get-error-axios-message";
import { Stack } from "expo-router";
import { Linking } from "react-native";
import { useToast } from "react-native-toast-notifications";

const LoginScreen = () => {
  const { login, isPendingLogin } = useAuthContext();
  const toast = useToast();

  const onLoginSubmit = (data: LoginFormData) => {
    login(data.email, data.password, {
      onSuccess: (data) => {
        toast.show("Hello, " + data.user.username, { type: "success" });
      },
      onError: (error) => {
        toast.show(getErrorAxiosMessage(error), { type: "danger" });
      }
    });
  }

  return (
    <>
    <Stack.Screen options={{ title: "Sign in" }} />
    <Content>
      <Panel>
        <ThemedText type="subtitle" className="text-center mb-2">Login</ThemedText>
        <ThemedText className="text-center mb-2">Welcome back! Please sign in to continue.</ThemedText>
        <LoginForm onSubmit={onLoginSubmit} isLoading={isPendingLogin} />
        <Divider className="mb-3 mt-3" />
        <Button variant="link" onPress={() => Linking.openURL(process.env.EXPO_PUBLIC_FRONTEND_REGISTER_URL as string)}>
          <ButtonText>Create a new account</ButtonText>
        </Button>
      </Panel>
    </Content>
    </>
  )
}

export default LoginScreen;