import { useEffect, useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import queryKeys from '../../services/queryKeys'

import BreadcrumbCom from '../breadcrumb/BreadcrumbCom'
import TablePaginatedWrapper from '../tableWrapper/TablePaginatedWrapper'
import Icons from '../Icons'
import { getProductsTemplate, setProductsTemplate } from '../../services/siteServices'
// import getDateTimeFromDateString from '../../helpers/getDateTimeFromDateString'

export default function ProductTemplates() {

    const queryClient = useQueryClient()

    const [selected, setSelected] = useState('')

    const [page, setPage] = useState(1)
    const [filter, setFilter] = useState({type: '', id: ''})
    const [willFilter, setWillFilter] = useState(false)

    const handleFilter = ({target:{name, value}}) => {
        setFilter(prev => ({...prev, [name]:value}))
    }

    const handleFilterByParams = () => {
        if(filter.type && !filter.id){
            return
        }else if(!filter.type){
            setPage(1)
            setWillFilter(prev => !prev)
            setFilter({type: '', id: ''})
        }else{
            setPage(1)
            setWillFilter(prev => !prev)
        }
    }

    const {data, isFetching, isError, error} = useQuery({
        queryKey: [...queryKeys.products_template, page, willFilter],
        queryFn: () => {
            const filterData = filter?.type ? {[filter?.type]: filter.id} : {}
            const reqData = {
                page,
                ...filterData
            }
            return getProductsTemplate(reqData)
        },
        staleTime: 0 //0 mins
    })
    // const productsTemData = data?.data?.templates // PRODUCTS TEMPLATE LIST
    // const pagination = data?.data?.pagination
    // console.log('DATA', data?.data)
    const [productsTemData, setProductsTemData] = useState([])
    const [pagination, setPagination] = useState({})
    useEffect(()=>{
        if(data){
            setProductsTemData(data?.data?.templates)
            setPagination(data?.data?.pagination)
        }
    },[data])


    const statusChange = useMutation({
        mutationFn: (fields) => {
            return setProductsTemplate(fields)
        },
        onError: (error) => {
        },
        onSuccess: (res) => {
            queryClient.refetchQueries({
                queryKey: [...queryKeys.country_list],
                // type: 'active',
                // exact: true,
            })
        },
        onSettled: () => {
            setSelected('')
        }
    })

    //FUNCTION TO CHANGE STATUS OR SIGNUP
    const handleStatusChange = (event, details) => {
        setSelected(event.target.id)
        const name = event.target.name
        const val = name.toUpperCase() === 'STATUS' ? details.status : details.signup
        const reqData = {
            'val_type': name.toUpperCase(),
            'country_uid': details?.country_uid,
            'code': details?.code,
            'val': val === 0 ? 1 : 0
        }
        statusChange.mutate(reqData)

        setTimeout(()=>{
            setSelected('')
            const NewData = productsTemData.map(item => { // remove later
                if(item.product_id === event.target.id){
                    return ({...item, status: !item.status})
                }else{
                    return item
                }
            })
            setProductsTemData(NewData)
        },3000) // remove later
    };

    return (
        <div className='w-full flex flex-col gap-8'>
            <BreadcrumbCom title='Product Templates' paths={['Dashboard', 'Product Templates']} />

            <div className='box bg-white dark:bg-black-box text-black-body dark:text-white-body'>
                { isError ?
                    <p className='text-red-500'>{error?.message}</p>
                    :
                    <>
                        {/* filter section */}
                        <div className='px-2 py-2 mb-4 flex flex-col sm:flex-row flex-wrap sm:items-center gap-2'>
                            <Icons name='filter' className='text-3xl' />
                            <div className='w-full sm:max-w-48'>
                                <select name='type' value={filter?.type} className='h-10 w-full p-2 rounded-md' onChange={handleFilter}>
                                    <option value=''>All</option>
                                    <option value='product_id'>Product ID</option>
                                    <option value='provision_name'>Provision Name</option>
                                </select>
                            </div>
                            <div className='w-full sm:max-w-48'>
                                <input name='id' value={filter?.id} disabled={!filter.type} className={`h-10 w-full p-2 rounded-md outline-none border border-black-aside ${!filter.type && 'opacity-30'}`} onChange={handleFilter} />
                            </div>
                            <button onClick={handleFilterByParams} disabled={filter.type && !filter.id} className={`h-10 bg-primary px-2 py-1 rounded-md text-white font-medium sm:self-end ${(filter.type && !filter.id) && 'opacity-50'}`}>Submit</button>
                        </div>
                        {/* end of filter section */}

                        <TablePaginatedWrapper data={productsTemData} isFetching={isFetching} setPage={setPage} itemsPerPage={pagination?.limit} pagination={pagination}>
                            {({ data }) => (
                                <>
                                    <table className="py-2 w-full text-sm">
                                        <thead className="py-2 text-sm text-slate-500 text-left">
                                        <tr>
                                            <th scope="col" className="px-2 py-2">
                                                Product ID
                                            </th>
                                            <th scope="col" className="px-8">
                                                Provision Name
                                            </th>
                                            <th scope="col" className="px-2 text-center">
                                                Status
                                            </th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        {(data && data.length > 0) ? data?.map((item, index) => (
                                                <tr key={index} className="py-2 border-t border-dashed border-slate-300">
                                                    <td className="px-2 py-2">
                                                        <div className='w-full min-w-48 flex items-center gap-2 whitespace-nowrap'>
                                                            <div className="text-left">
                                                                <div className="text-base font-semibold">{item?.product_id}</div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td className="px-8">
                                                        <div className="text-left">
                                                            <div className="text-base font-semibold">{item?.provision_name}</div>
                                                        </div>
                                                    </td>
                                                    <td className="px-2">
                                                        <div className="flex justify-center">
                                                            <>
                                                                {selected === item?.product_id ?
                                                                    <div role="status" className="text-center">
                                                                        <svg aria-hidden="true" className="w-4 h-4 text-gray-200 animate-spin dark:text-gray-600 fill-primary" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                            <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
                                                                            <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
                                                                        </svg>
                                                                        <span className="sr-only">Loading...</span>
                                                                    </div>
                                                                :
                                                                    <input 
                                                                        className="w-4 h-4 cursor-pointer text-primary bg-gray-100 border-gray-300 rounded-sm focus:ring-primary/80 dark:focus:ring-primary dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                                                                        onChange={(e)=>handleStatusChange(e, item)}
                                                                        type="checkbox" 
                                                                        checked={item?.status} 
                                                                        name="status" 
                                                                        id={item?.product_id} 
                                                                    />
                                                                }
                                                            </>
                                                        </div>
                                                    </td>
                                                </tr>
                                            ))
                                            :
                                            <tr className="py-2 border-t border-dashed border-slate-300">
                                                <td className="px-3 py-2" colSpan={4}>
                                                    <div className="flex justify-center items-center">
                                                        No Record Found
                                                    </div>
                                                </td>
                                            </tr>
                                        }
                                        </tbody>
                                    </table>
                                </>
                            )}
                        </TablePaginatedWrapper>
                    </>
                }
            </div>
        </div>
    )
}