import {useLocation, useNavigate, Link} from 'react-router-dom'
import { useQuery, useMutation } from '@tanstack/react-query'
import { FaCaretDown } from "react-icons/fa";
import BreadcrumbCom from '../breadcrumb/BreadcrumbCom'
import {useEffect, useState} from 'react';
import RouteLinks from '../../RouteLinks';
import { getSubscriptionsView, updateTemplate } from '../../services/siteServices'
import queryKeys from '../../services/queryKeys'
import getDateTimeFromDateString from '../../helpers/getDateTimeFromDateString';

export default function SubscriptionViewCom() {


    const {state} = useLocation()
    const navigate = useNavigate()

    const [reqStatus, setReqStatus] = useState({loading: false, type: '', error: false, success: false})

    const [values, setValues] = useState({custom_id: '', template_uid: ''})

    const handleValueChange = ({target:{name, value}}) => {
        if(name == 'custom_template'){
            setValues(prev => ({...prev, custom_id: value}))
        }else if (name == 'template') {
            setValues(prev => ({...prev, template_uid: value}))
        }else{
            setValues(prev => ({...prev}))
        }
    }

    useEffect(() => {
        if (!state?.subscriptionUID) {
            navigate(RouteLinks.homePage, {replace: true})
        }
    }, [])

        const {data, isFetching, isError, error} = useQuery({
        queryKey: queryKeys.subscriptions_view,
        queryFn: () => {
            // const filterData = filter?.type ? {[filter?.type]: filter.id} : {}
            const reqData = {
                subscription_uid: state?.subscriptionUID
                // page,
                // ...filterData
            }
            return getSubscriptionsView(reqData)
        },
        staleTime: 0 //0 mins
    })
    const subscriptionViewData = data?.data // ACCOUNT VIEW DATA
    const customTemplates = subscriptionViewData?.available_custom_templates
    const availableTemplates = subscriptionViewData?.available_templates
    const selectedSubscription = subscriptionViewData?.subscription
    // console.log('subscriptionViewData', subscriptionViewData)


    const templateUpdate = useMutation({
        mutationFn: (fields) => {
            setReqStatus(prev => ({...prev, loading: true}))
            return updateTemplate(fields)
        },
        onError: (error) => {
            setReqStatus(prev => ({...prev, loading: false, error: true}))
        },
        onSuccess: (res) => {
            setReqStatus(prev => ({...prev, loading: false, error: false, success: true}))
        },
        onSettled: () => {
            setTimeout(()=>{
                setReqStatus({loading: false, type: '', error: false, success: false})
            }, 3000)
        }
    })

    const handleUpdateTemplate = ({target:{name}}) => {
        setReqStatus({loading: false, type: name, error: false, success: false})
        const reqData = {Subscrtiption_uid: state?.subscriptionUID}
        if(name == 'template'){
            reqData.template_uid = values.template_uid
        }else if (name == 'custom_template'){
            reqData.custom_id = values.custom_id
        }else{
            return
        }
        console.log('req', reqData)
        templateUpdate.mutate(reqData)
    }


    return (
        <div className='w-full flex flex-col gap-8'>
            <BreadcrumbCom title={`Subscription View [${state?.subscriptionUID}]`} paths={['Dashboard', 'Subscription View']}/>

            {isFetching ? 
            <>
                <p className='text-slate-800'>Loading...</p>
            </>
            : isError ?
                <p className='text-red-500'>{error.message}</p>
            :
                <>
                    <div className='w-full box bg-white dark:bg-black-box text-black-body dark:text-white-body overflow-x-auto'>
                        <table className="py-2 w-full text-sm bg-[aliceblue] dark:bg-transparent rounded-[10px]">
                            <tbody>
                                <tr className="py-2 border-t border-dashed border-slate-300">
                                    <td className="px-2 py-2">
                                        <div className="text-left">
                                            <div className="text-base font-semibold">{getDateTimeFromDateString(selectedSubscription?.added)}</div>
                                        </div>
                                    </td>
                                    <td className="px-2">
                                        <div className="text-left">
                                            <div className="text-base font-semibold">{selectedSubscription?.product_id}</div>
                                        </div>
                                    </td>
                                    <td className="px-2">
                                        <div className="text-left">
                                            <div className="text-base font-semibold">{selectedSubscription?.internal_url}
                                            <br /><span>Template :</span> {selectedSubscription?.product_template}
                                            <br /><span>Custom :</span> {selectedSubscription?.custom_template}
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-2">
                                        <div className="text-right">
                                            <div className="text-base font-semibold">{selectedSubscription?.status}</div>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div className='box bg-white dark:bg-black-box text-black-body dark:text-white-body'>

                        <div className='w-full'>
                            <label className='font-medium'>Assign Template</label>
                            <div className='flex flex-col xs:flex-row md:items-center gap-2'>
                                <div className='w-full h-10 relative overflow-hidden rounded-md'>
                                    <select name='template' value={values.template_uid} onChange={handleValueChange} className='w-full h-full p-2 appearance-none dark:bg-transparent border-0 dark:border-1 border-white ring-0 outline-none'>
                                        <option value=''>None</option>
                                        {availableTemplates && availableTemplates.map(item => (
                                            <option key={item?.template_uid} value={item?.template_uid}>{`${item?.product_id}-${item?.provision_name}`}</option>
                                        ))}
                                    </select>
                                    <FaCaretDown className='text-base absolute top-1/2 -translate-y-1/2 right-2' />
                                </div>
                                <button name='template' onClick={handleUpdateTemplate} disabled={(reqStatus.loading || !values.template_uid)} className={`rounded-md p-2 bg-primary text-white text-center ${(reqStatus.loading || !values.template_uid) && 'opacity-50'}`}>Update</button>
                            </div>
                            {(reqStatus.type == 'template' && (reqStatus.error || reqStatus.success)) &&
                                <p className={`p-2 mt-4 ${reqStatus.success ? 'text-emerald-500' : 'text-red-500'}`}>{reqStatus.success ? 'Template updated' : 'Unable to complete request, try again'}</p>
                            }
                        </div>
                    </div>

                    <div className='box bg-white dark:bg-black-box text-black-body dark:text-white-body'>

                        <div className='w-full'>
                            <label className='font-medium'>Assign Custom Template</label>
                            <div className='flex flex-col xs:flex-row md:items-center gap-2'>
                                <div className='w-full h-10 relative overflow-hidden rounded-md'>
                                    <select name='custom_template' value={values.custom_id} onChange={handleValueChange} className='w-full h-full p-2 appearance-none dark:bg-transparent border-0 dark:border-1 border-white ring-0 outline-none'>
                                        <option value=''>None</option>
                                        {customTemplates && customTemplates.map(item => (
                                            <option key={item?.custom_id} value={item?.custom_id}>{`${item?.custom_id}-${item?.provision_name}`}</option>
                                        ))}
                                    </select>
                                    <FaCaretDown className='text-base absolute top-1/2 -translate-y-1/2 right-2' />
                                </div>
                                <button name='custom_template' onClick={handleUpdateTemplate} disabled={(reqStatus.loading || !values.custom_id)} className={`rounded-md p-2 bg-primary text-white text-center ${(reqStatus.loading || !values.custom_id) && 'opacity-50'}`}>Update</button>
                            </div>
                            {(reqStatus.type == 'custom_template' && (reqStatus.error || reqStatus.success)) &&
                                <p className={`p-2 mt-4 ${reqStatus.success ? 'text-emerald-500' : 'text-red-500'}`}>{reqStatus.success ? 'Template updated' : 'Unable to complete request, try again'}</p>
                            }
                        </div>
                    </div>
                </>
            }
        </div>
    )
}