import React, { useRef, useState } from "react";
import {useNavigate} from 'react-router-dom'
import getImage from "../../utils/getImage";
import { Modal } from "bootstrap";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { subscribe } from '../../services/services'
import queryKeys from "../../services/queryKeys";

export default function ProductStart(props){

    const queryClient = useQueryClient()
    const navigate = useNavigate()

    const [requestStatus, setRequestStatus] = useState({status:false, message: ''})
    const product_uid = props?.productData?.product_uid;
    const product_id = props?.productData?.product_id;
    const productBanner = `product/${props.productData?.banner}`;
    const productTitle  = props?.productData?.title;
    const productDescription  = props?.productData?.description;
    const promotion_text  = props?.productData?.promotion_text;
    const product_status  = props?.productData?.status;
    const saleText  = props?.productData?.sale_text;

    const modalRef = useRef(null)

    const invalidate = () => {
        // queryClient.refetchQueries({
        //     queryKey: [...queryKeys.product],
        //     // type: 'active',
        //     // exact: true,
        // })
        queryClient.invalidateQueries({ queryKey: [...queryKeys.product_url] })
        queryClient.invalidateQueries({ queryKey: [...queryKeys.product_page] })
    }

    const mutation = useMutation({
        mutationFn: (fields) => {
            return subscribe(fields)
        },
        onError: (error) => {
            setRequestStatus({status:false, message:'failed, try again'})
            console.log('ERROR IS', error)
        },
          onSuccess: (res) => {
            setRequestStatus({status:true, message:'successful'})
            navigate(`/product/${product_id}`, {replace: true}) //'/product/'+ product_id
            dismissModal()
            console.log(res)
        },
        onSettled: () => {
            invalidate() // Invalidates selected queries
            setTimeout(()=>{
                setRequestStatus({status:false, message:''})
            },4000)
        }
    })

    const handleSubscribe = () => {
        mutation.mutate({product_id: product_id})
    }

    const dismissModal = () => {
        const body = document.querySelector('body')
        body.removeAttribute('style')
        // body.classList.toggle('modal-open')

        const modalBackdrop = document.querySelectorAll('.modal-backdrop')
        modalBackdrop.forEach(item => {
            if (item) {
                item.remove();
            }
        })
        
        const modal = Modal.getInstance(modalRef.current);
        modal && modal.hide();
    };

    return (
        <>
            <div className="row">
                <div className="col-md-9">
                    <div className="card card-statistics ">
                        <img className="card-img-top" src={getImage(productBanner)}  alt="Card image cap" />
                        <div className="card-body">
                            <h4 className="card-title">{productTitle}</h4>
                            <div className="card-text" style={{fontSize: '14px'}} dangerouslySetInnerHTML={{__html: productDescription}}/>
                            {/* <p className="card-text">{productDescription}</p> */}
                        </div>
                    </div>
                </div>
                <div className="col-md-3">
                    {
                        (product_status===1) ? <>
                            <div className="card card-statistics mb-30 panel_coming_soon_c3">
                                <>
                                    <img className="card-img-top" src={getImage('widget/coming-soon.jpg')} alt="Card image cap" />
                                </>

                                <div className="card-body">
                                    <p className="card-text">We are actively working to launch this feature soon and will keep you informed every step of the way. </p>
                                </div>
                                <ul className="list-group list-group-flush">
                                    <li className="list-group-item"><h4>Coming soon!!!</h4></li>
                                    <li className="list-group-item"></li>
                                </ul>
                            </div>
                        </> : <>
                            <div className="card card-statistics mb-30 panel_round_c3">
                                {/*<img className="card-img-top" src={getImage('widget/01.jpg')} alt="Card image cap" />*/}
                                <div className="card-body">
                                    <h4 className="card-title">Subscription</h4>
                                    <p className="card-text">Launch your <span style={{color: '#148399' , fontWeight: 'bolder'}}>{productTitle}</span> with us for free! Benefit from our dedicated support and customize features that align perfectly with your goals. Experience everything at no cost! </p>
                                </div>
                                <ul className="list-group list-group-flush">
                                    <li className="list-group-item"><h4>{promotion_text}</h4></li>
                                    <li className="list-group-item">90 days free and $5.99/Month</li>
                                    <li className="list-group-item"></li>
                                </ul>
                                <div  className="subscribe-box">
                                    <button className="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#verticalCenter">Activate Now!</button>
                                </div>
                            </div>
                        </>
                    }
                </div>
            </div>

            {/* Vertical Center Modal */}
            <div ref={modalRef} className="modal fade" id="verticalCenter" tabIndex="-1" role="dialog" aria-hidden="true">
                <div className="modal-dialog modal-dialog-centered" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title" style={{fontSize: '18px'}} id="verticalCenterTitle">{productTitle}</h5>
                            <button type="button" className="close" data-bs-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div className="modal-body">
                            <div style={{fontSize: '18px'}} className="" dangerouslySetInnerHTML={{__html: saleText}}/>
                            {/* {mutation.error &&
                            <>
                                <div className="col-12">
                                <p className='text-danger'>{mutation.error.message}</p>
                            </div>
                            </>
                            }
                             {mutation.isSuccess &&
                            <>
                                <div className="col-12">
                                    <p className='text-success'>{'subscription is successful'}</p>
                                </div>
                            </>
                            } */}
                            {requestStatus.message && (
                            <div className="col-12">
                                <p className={`p-2 text-center ${requestStatus.status ? 'text-success' : 'text-danger'}`}>{requestStatus.message}</p>
                            </div>
                            )}
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" className="btn btn-primary" disabled={mutation.isSuccess} onClick={handleSubscribe}>{mutation.isPending ? 'activating...' : 'Start Activation'}</button>
                        </div>
                    </div>
                </div>
            </div>
            {/* END of Vertical Center Modal */}
        </>
    )
}