import {useEffect} from "react";
import { useMutation, useQuery } from '@tanstack/react-query'
import BreadcrumbComBS from "../breadcrumb/BreadcrumbComBS";
// import getImage from "../../utils/getImage";
import ProductStart from "./ProductStart";
import { useLocation } from 'react-router-dom';
import {MyProductData} from "../../services/services";
import ProductActive from "./ProductActive";
import ProductProvision from "./ProductProvision";
import {productConst} from "../../constants/products";

export default function ProductFactory(){
    const location = useLocation();
    const pathname = location.pathname;

    // Split the pathname by '/' and get the last element
    const productID = pathname.split('/').pop();

    const getProductData = useMutation({
        mutationFn: (reqData) => {
            return MyProductData(reqData)
        },
        onError: (error) => {
            console.log(error)
        },
        onSuccess: (res) => {
            if(res?.data?.resultCode != '0'){
                throw({message: 'Something went wrong'})
            }
        }
    })

    useEffect(()=>{
    let reqData = {
        product_id : productID,
        token: localStorage.getItem('token'), // USER TOKEN
        uid: localStorage.getItem('uid') // USER UID
    }
    getProductData.mutate(reqData)
    },[])
        
    const myproduct_data = getProductData?.data?.data?.myproduct?.myproudct // PRODUCT DETAILS
    const product_name =  myproduct_data?.product_name;
    const product_status  = myproduct_data?.status;

    return(
        <>
            <BreadcrumbComBS title={product_name} paths={['Dashboard', 'Product']} />
            <div className="row">
                {getProductData?.isPending ?
                    <>
                        <div className="row">
                            <div className="col-12">
                                <p className='text-mute'>Loading...</p>
                            </div>
                        </div>
                    </>
                    : getProductData?.error ?
                        <div className="row">
                            <div className="col-12">
                                <p className='text-danger'>{getProductData?.error?.message}</p>
                            </div>
                        </div>
                        :
                <div>
                    {(product_status <= productConst.PRODUCT_AVAILABLE)?
                        <ProductStart productData={myproduct_data} />
                        :<></> }

                     {(product_status === productConst.PRODUCT_PROVISIONING)?
                        <ProductProvision productData={myproduct_data} />
                        :<></> }

                    {(product_status === productConst.PRODUCT_ACTIVE)?
                        <ProductActive productData={myproduct_data} />
                        :<></> }

                </div>
               }
            </div>
        </>
    )
}