"use client";

import { FC, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useSelector } from "react-redux";
import { Button, Text } from "@mantine/core";
import { Auth } from "@/client";
import SCOPES from "@/constants/scopes";
import { Scopes } from "@/enums/Scopes";
import { notifications } from "@/lib/notifications";
import { RootState } from "@/lib/store/store";

const ConsentButton: FC = () => {
    const searchParams = useSearchParams();
    const auth = useSelector((state: RootState) => state.auth);
    const [clientName, setClientName] = useState<string>(Scopes.UNDEFINED);
    const [serviceRequiredAccess, setServiceRequiredAccess] =
        useState<string>("");

    const setAccessesForScope = () => {
        const accesses: string[] = [];
        (auth.scope ?? []).forEach((scopeItem: Scopes) => {
            const access = SCOPES[scopeItem];
            if (access) accesses.push(access);
        });
        setServiceRequiredAccess(accesses.join("\n"));
    };

    const requestConsent = () => {

    };

    useEffect(() => {
        setAccessesForScope();
        requestConsent();
    }, []);

    const confirmAccess = () => {
        const phoneNumber = auth.phoneNumber;
        if (!phoneNumber) {
            console.error("Phone number is not set");
            return;
        }
        const consentChallenge = searchParams.get("consent_challenge");
        if (!consentChallenge) {
            console.error("Consent challenge is missing in the URL");
            return;
        }
        Auth.postAuthConsentAccept({
            body: {
                consent_challenge: consentChallenge,
                phone_number: phoneNumber,
            },
        })
            .then(response => response.data)
            .then(response => {
                if (!response) {
                    console.error("Response is empty");
                    return;
                }
                const { redirect_url, ok, message } = response;
                notifications.guess(ok, { message });

                if (redirect_url) {
                    window.location.href = redirect_url;
                } else {
                    console.error("Redirect URL is missing in the response");
                }
            });

    };

    return (
        <>
            <Button
                onClick={() => confirmAccess()}
                variant={"filled"}>
                Войти
            </Button>
            <Text
                fz={"h4"}
                ta="center">
                Сервис {clientName} получит {serviceRequiredAccess}
            </Text>
        </>
    );
};

export default ConsentButton;
