import React, {memo} from 'react'
import getImage from "../../../utils/getImage";
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import queryKeys from '../../../services/queryKeys';
import { getProductTemplateData, activateTemplate } from '../../../services/services';

const SiteTemplateSelector = memo(({name='Full Name', data, productData}) =>{

        const queryClient = useQueryClient()

        const {data:templateData, isFetching, isError, error} = useQuery({
            queryKey: queryKeys.productTemplateData,
            queryFn: () => {
                let reqData = {
                    token: localStorage.getItem('token'), // USER TOKEN
                    uid: localStorage.getItem('uid'), // USER UID
                    product_id: productData?.product_id
                }
            return getProductTemplateData(reqData)
            },
            staleTime: 0
        })

        const templateResponse = templateData?.data
        const currentTemUID = templateResponse?.current_template_uid
        const templates = templateResponse?.templates

        // console.log('data Template', templateResponse)
        // console.log("Page data == ", data)

        const handleActivateTemplate = useMutation({
            mutationFn: (fields) => {
                return activateTemplate(fields)
            },
            onSuccess: (res) => {
                if(res?.data?.resultCode != '0'){
                    throw new Error(res.data.resultDescription)
                }
                queryClient.refetchQueries({  // refetches productProvision API call
                    queryKey: [...queryKeys.settingsData],
                })
            },
            onSettled: () => {
                setTimeout(()=>{
                    handleActivateTemplate.reset()
                }, 3000)
            }
        })

        const handleSubmit = (tem_uid) => {
            const reqData = {
                token: localStorage.getItem('token'), // USER TOKEN
                uid: localStorage.getItem('uid'), // USER UID
                product_id: productData?.product_id,
                template_uid: tem_uid
            }
            // console.log(reqData)
            handleActivateTemplate.mutate(reqData)
        }

        return (
            <div className="page-account-form">
                <div className="p-0">
                    {isFetching ? 
                    <>
                        <div className="row">
                            <div className="col-12">
                                <p className='text-mute'>Loading...</p>
                            </div>
                        </div>
                    </>
                    : isError ?
                    <div className="row">
                        <div className="col-12">
                            <p className='text-danger'>{error?.message}</p>
                        </div>
                    </div>
                    :
                    <div className="row">
                        <>
                        {!templates?.length ?
                            <p>No data Found</p>
                            :
                            templates.map(template => (
                                <div key={template.template_uid} className="col-xl-6 col-sm-6">
                                    <div className="card card-statistics">
                                        <div className="card-body">
                                            <div className="text-center p-2">
                                                <div className="mb-2">
                                                    <img  src={getImage('file-icon/svg.png')} alt={template.title} />
                                                </div>
                                                <h4 className="mb-0">{template.title}</h4>
                                                {currentTemUID == template.template_uid ?
                                                <button className="btn btn-light" disabled={true}>Active</button>
                                                :
                                                <button onClick={()=>handleSubmit(template.template_uid)} className="btn btn-primary">Activate</button>
                                                }
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))
                        }
                            {/* {Object.entries(data)?.map(([key, value]) => (
                                <div key={key} className="col-xl-6 col-sm-6">
                                    <div className="card card-statistics">
                                        <div className="card-body">
                                            <div className="text-center p-2">
                                                <div className="mb-2">
                                                    <img  src={getImage(value.banner)} alt={value.title} />
                                                </div>
                                                <h4 className="mb-0">{value.title}</h4>
                                                <a href="javascript:void(0)" className="btn btn-light">Activate</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))} */}
                        </>
                        
                        <div className="col-12">
                            <>
                            {handleActivateTemplate.isPending ?
                            <p className={'text-center '}>loading...</p>
                            :
                            handleActivateTemplate.isError ?
                            <p className={'text-center text-danger'}>{handleActivateTemplate.error.message}</p>
                            :
                            handleActivateTemplate.isSuccess?
                            <p className={'text-center text-success'}>Templated activated successfully</p>
                            :
                            null
                            }
                            </>
                        </div>
                    </div>
                    }
                </div>
            </div>
        )
    }
)
export default SiteTemplateSelector