import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";

const SubscriptionButton = ({ clientId, customerId, subscriptionStatus, subscriptionId }) => {
    const router = useRouter();
    const [buttonState, setButtonState] = useState("Subscribe");
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        if (subscriptionStatus === "active") {
            setButtonState("Cancel");
        } else if (subscriptionStatus === "canceled") {
            setButtonState("Activate");
        } else {
            setButtonState("Subscribe");
        }
    }, [subscriptionStatus]);

    const handleClick = async () => {
        setIsLoading(true);
        try {
            if (buttonState === "Cancel") {
                // Show confirmation dialog
                if (
                    window.confirm(
                        "Are you sure you want to cancel your subscription? Canceling your subscription will remove your access to our services."
                    )
                ) {
                    const response = await fetch("/api/stripe-cancel-subscription", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ subscriptionId }),
                    });
                    console.log(subscriptionId);
                    const result = await response.json();
                    if (result.success) {
                        alert("Your subscription has been cancelled.");
                        setButtonState("Activate");
                    } else {
                        alert("Failed to cancel subscription. Please try again or contact support.");
                        console.log("Failed to cancel subscription:", result.error);
                    }
                }
            } else {
                const response = await fetch("/api/stripe-create-portal-session", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ clientId, customerId }),
                });
                const { url } = await response.json();
                window.location.href = url;
            }
        } catch (error) {
            console.error("Error handling subscription action:", error);
            alert("An error occurred. Please try again or contact support.");
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <button className="btn btn-no-arrow" onClick={handleClick} disabled={isLoading}>
            {isLoading ? "Loading..." : buttonState}
        </button>
    );
};

export default SubscriptionButton;
