import {
    useStripe,
    useElements,
    PaymentElement
} from "@stripe/react-stripe-js";
import React, { useEffect, useState } from "react";
import { useGlobalContext } from "@/context/Provider";
import { Button } from "../ui/button";
import { useSearchParams } from "next/navigation";
import Loader from "../common/loader";

const CheckoutForm = (props: any) => {
    const { Toast, } = useGlobalContext()
    const searchParams = useSearchParams();
    const queryParams = Object.fromEntries(searchParams.entries());
    const [message, setMessage] = useState(null) as any;
    const stripe = useStripe();
    const [loading, setLoading] = useState(false)
    const elements: any = useElements();

    const handleSubmit = async (e: any) => {
        e.preventDefault()
        debugger
        try {
            setLoading(true);
            if (!stripe || !elements) {
                Toast.error("Payment service is not available. Please try again later.");
                return;
            }
            const baseUrl = window.location.origin;
            const returnUrl = `${baseUrl}/success?price=${queryParams?.price}`;
            const { error } = await stripe.confirmPayment({
                elements,
                confirmParams: {
                    return_url: returnUrl,
                },
            });
            if (error) {
                // Toast.error(error.message || "An error occurred while processing the payment.");
                throw new Error(error.message || "Payment confirmation error.");
            }
        } catch (error: any) {
            const errorMessage = typeof error === "string" ? error : error?.message || "An unexpected error occurred.";
            Toast.error(errorMessage);
        } finally {
            setLoading(false);
        }
    };



    useEffect(() => {
        if (!stripe) {
            return;
        }
        const clientSecret = new URLSearchParams(window.location.search).get(
            'payment_intent_client_secret'
        );
        if (!clientSecret) {
            return;
        }
        stripe.retrievePaymentIntent(clientSecret).then(({ paymentIntent }) => {
            switch (paymentIntent?.status) {
                case 'succeeded': {
                    setMessage('Payment succeeded!');
                    break;
                }
                case 'processing':
                    setMessage('Your payment is processing.');
                    break;
                case 'requires_payment_method':
                    setMessage('Your payment was not successful, please try again.');
                    break;
                default:
                    setMessage('Something went wrong.');
                    break;
            }
        });
    }, [stripe]);
    return (
        <>
            <form onSubmit={handleSubmit}  >
                <div>
                    <div className="w-full max-h-[400px] overflow-x-hidden overflow-y-scroll">
                        <PaymentElement id="payment-element" />
                    </div>
                    <div className="w-full">
                        <div className='pt-4 flex justify-end'>
                            <Button variant={"default"} className="px-4 mb-3 theme-background text-white d-flex align-items-center justify-content-center" type="submit" ><Loader loading={loading} />Pay ${queryParams?.price}</Button>
                        </div>
                    </div>
                </div>
            </form>
        </>
    );
};

export default CheckoutForm;