"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 { Auth } from "@/client";
import PhoneInput from "@/components/ui/PhoneInput/PhoneInput";
import { notifications } from "@/lib/notifications";
import {
    setLoginChallenge,
    setPhoneNumber,
} from "@/lib/store/features/auth/authSlice";
import { useAppDispatch } from "@/lib/store/store";

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) => {
        const phoneNumber = values.phoneNumber.replace(/ /g, "");
        dispatch(setPhoneNumber(phoneNumber));
        Auth.postAuthOtpRequest({
            body: { phone_number: phoneNumber },
        })
            .then(response => response.data)
            .then(response => {
                console.log(response);
                if (!response) {
                    notifications.error({
                        message: "Ошибка при отправке запроса",
                    });
                    return;
                }
                const { ok, message } = response;
                notifications.guess(ok, { message });
                if (ok) {
                    router.push("/verify-phone");
                }
            });
    };

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

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

    return (
        <form
            style={{ justifyItems: "center" }}
            onSubmit={form.onSubmit(handleSubmit)}>
            <Stack maw={500}>
                <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;
