"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";

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 = () => {
        // if (!auth.loginChallenge || auth.scope.length === 0) return;
        // new AuthService()
        //     .requestConsent(auth.loginChallenge)
        //     .then(response => response.data)
        //     .then(({ clientName }) => {
        //         setClientName(clientName);
        //     })
        //     .catch(error => {
        //         console.error(error);
        //         notifications.error({ message: error.toString() });
        //     });
    };

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

    const confirmAccess = () => {
        const consentChallenge = searchParams.get("consent_challenge");
        if (!consentChallenge) {
            console.error("Consent challenge is missing in the URL");
            return;
        }
        Auth.postAuthConsentAccept({
            body: { consent_challenge: consentChallenge },
        })
            .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");
                }
            });
        // if (!auth.loginChallenge) return;
        // new AuthService()
        //     .approveConsent(auth.loginChallenge)
        //     .then(response => response.data)
        //     .then(({ redirectUrl }) => {
        //         window.location.href = redirectUrl;
        //     })
        //     .catch(error => {
        //         console.error(error);
        //         notifications.error({ message: error.toString() });
        //     });
    };

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

export default ConsentButton;
