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';
import {Link} from "react-router-dom";
import siteLinks from "../../../links/siteLinks";

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
        const custom_template_name = templateResponse?.custom_template_name

        // 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)
        }
        if (custom_template_name && custom_template_name != '') {
            // This implies we have a custom template , just return here
            return <>
                <div className='col-12'>
                    <div
                        className="rounded-2 d-flex flex-column justify-content-between align-items-center"
                        style={{backgroundColor: '#F2FAF7'}}>
                        <h4 className='p-4 text-black'
                            style={{marginBottom: '20px'}}>Custom Product Template.</h4>
                        <img className='' style={{width: '200px'}}
                             src={getImage('custom-template.png')}
                             alt='mail-alert'/>
                        <h4 className='p-4 text-black'
                            style={{marginTop: '20px'}}>This product is using a custom template named <span
                            style={{color: 'darkred'}}>&ldquo;{custom_template_name}&rdquo;</span> .</h4>
                    </div>
                </div>

            </>
        }
        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 overflow-y-auto" style={{maxHeight: '550px'}}>
                                <>
                                    {!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