"use client";

import { FC, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button, Stack } from "@mantine/core";
import { useForm } from "@mantine/form";
import PhoneInput from "@/components/PhoneInput/PhoneInput";
import { useAppDispatch } from "@/lib/store";
import { setLoginChallenge, setPhoneNumber } from "@/lib/features/auth/authSlice";
import { AuthService } from "@/mocks/authService";
import { notifications } from "@/lib/notifications";

type LoginForm = {
    phoneNumber: string;
};

type Props = {
    loginChallenge?: string;
    isCreatingId?: boolean;
};

const LoginForm: FC<Props> = ({ loginChallenge, isCreatingId = false }) => {
    const [phoneMask, setPhoneMask] = useState<string>("");
    const router = useRouter();
    const form = useForm<LoginForm>({
        initialValues: {
            phoneNumber: "",
        },
        validate: {
            phoneNumber: phoneNumber =>
                phoneNumber.length !== phoneMask.length &&
                "Введите корректный номер",
        },
    });
    const dispatch = useAppDispatch();

    useEffect(() => {
        dispatch(setLoginChallenge(loginChallenge ?? null));
    }, [loginChallenge]);

    const handleSubmit = (values: LoginForm) => {
        dispatch(setPhoneNumber(values.phoneNumber));

        new AuthService().requestLogin(values.phoneNumber)
            .then(response => response.data)
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                } else {
                    router.push("/verify-phone");
                }
            })
            .catch(error => {
                console.error(error);
                notifications.error({ message: error.toString() });
            })
    };

    const navigateToCreateId = () => router.push("/create-id");

    const navigateToLogin = () => router.push("/");

    return (
        <form onSubmit={form.onSubmit(handleSubmit)}>
            <Stack>
                <PhoneInput
                    {...form.getInputProps("phoneNumber")}
                    setPhoneMask={setPhoneMask}
                />
                {isCreatingId ? (
                    <>
                        <Button
                            variant={"filled"}
                            type={"submit"}>
                            Создать аккаунт
                        </Button>
                        <Button
                            variant={"outline"}
                            onClick={() => navigateToLogin()}>
                            Уже есть LogiDex ID
                        </Button>
                    </>
                ) : (
                    <>
                        <Button
                            variant={"filled"}
                            type={"submit"}>
                            Войти
                        </Button>
                        <Button
                            variant={"outline"}
                            onClick={() => navigateToCreateId()}>
                            Создать LogiDex ID
                        </Button>
                    </>
                )}
            </Stack>
        </form>
    );
};

export default LoginForm;
