"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 {
    setLoginChallenge,
    setPhoneNumber,
} from "@/lib/store/features/auth/authSlice";
import { notifications } from "@/lib/notifications";
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");
                }
            });
        // 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;
