"use client";

import { FC } from "react";
import { redirect } from "next/navigation";
import { useSelector } from "react-redux";
import { Button, PinInput, Stack } from "@mantine/core";
import { useForm } from "@mantine/form";
import ResendVerificationCode from "@/app/verify-phone/components/ResendVerificationCode/ResendVerificationCode";
import style from "@/app/verify-phone/components/VerifyPhoneForm/VerifyPhone.module.css";
import { Auth } from "@/client";
import { notifications } from "@/lib/notifications";
import { RootState } from "@/lib/store/store";

type VerifyNumberForm = {
    code: string;
};

const VerifyPhoneForm: FC = () => {
    const form = useForm<VerifyNumberForm>({
        initialValues: {
            code: "",
        },
        validate: {
            code: code => code.length !== 6 && "Введите весь код",
        },
    });
    const authState = useSelector((state: RootState) => state.auth);

    const handleSubmit = (values: VerifyNumberForm) => {

        if (!authState.phoneNumber || !authState.loginChallenge) return;
        console.log(authState.phoneNumber.replace(/ /g, ""));

        Auth.postAuthOtpVerify({
            body: {
                phone_number: authState.phoneNumber,
                login_challenge: authState.loginChallenge,
                otp: values.code,
            },
        })
            .then(response => response.data)
            .then(response => {
                if (!response) return;
                const { redirect_url, ok } = response;
                if (!ok) {
                    notifications.error({
                        message: "Ошибка при подтверждении номера",
                    });
                    return;
                }
                window.location.href = redirect_url;
            });
    };

    const navigateToLogin = () => redirect("/");

    return (
        <form
            style={{ justifyItems: "center" }}
            onSubmit={form.onSubmit(handleSubmit)}>
            <Stack maw={500}>
                <PinInput
                    length={6}
                    placeholder="_"
                    oneTimeCode
                    size={"md"}
                    classNames={{
                        root: style["pin-input-root"],
                        input: style["pin-input"],
                    }}
                    {...form.getInputProps("code")}
                />
                <Button
                    variant={"filled"}
                    type={"submit"}
                    disabled={form.values.code.length !== 6}>
                    Подтвердить
                </Button>
                <ResendVerificationCode />
                <Button
                    variant={"outline"}
                    onClick={navigateToLogin}>
                    Назад
                </Button>
            </Stack>
        </form>
    );
};

export default VerifyPhoneForm;
