import { useApi } from "@/api";
import { selectors } from "@/store";
import { useCallback, useEffect, useMemo, useState } from "react"
import { useSelector } from "react-redux";

interface IUseMakePaymentProps {
    productId: string;
    placementId: string;
    paywallId: string;
    returnPaidUrl?: string;
}

export const useMakePayment = ({
    productId,
    placementId,
    paywallId,
    returnPaidUrl = `https://${window.location.host}/payment/result/`
}: IUseMakePaymentProps) => {
    const api = useApi();
    const token = useSelector(selectors.selectToken);
    const [paymentIntentId, setPaymentIntentId] = useState<string>();
    const [paymentType, setPaymentType] = useState<"payment" | "setup">("payment");
    const [clientSecret, setClientSecret] = useState<string>();
    const [publicKey, setPublicKey] = useState<string>();
    const [returnUrl, setReturnUrl] = useState<string>();
    const [error, setError] = useState<string>();
    const [isLoading, setIsLoading] = useState(false);

    const makePayment = useCallback(async () => {
        if (!productId?.length || !placementId?.length || !paywallId?.length) {
            return;
        }
        try {
            setIsLoading(true);
            const res = await api.makePayment({
                token,
                productId,
                placementId,
                paywallId
            });

            if ("payment" in res && res.payment.status === "paid") {
                return window.location.href = `${returnPaidUrl}?redirect_status=succeeded`;
            }

            if ("status" in res && res.status === "paid") {
                return window.location.href = `${returnPaidUrl}?redirect_status=succeeded`;
            }

            if ("message" in res && res.message) {
                return setError(res.message);
            }

            if (!("data" in res) || !res.data) {
                return;
            }
            const { data, type } = res;
            setPaymentIntentId(data.paymentIntentId);
            setPaymentType(type);
            setClientSecret(data.client_secret);
            setReturnUrl(data.return_url);
            setPublicKey(data.public_key);
        } catch (error) {
            setError(error as string);
        } finally {
            setIsLoading(false);
        }
    }, [api, paywallId, placementId, productId, returnPaidUrl, token])

    useEffect(() => {
        makePayment()
    }, [makePayment])


    return useMemo(() => ({
        paymentIntentId,
        paymentType,
        clientSecret,
        returnUrl,
        publicKey,
        error,
        isLoading
    }), [
        clientSecret,
        error,
        isLoading,
        paymentIntentId,
        paymentType,
        publicKey,
        returnUrl
    ])
}