import React, { useRef, useState } from 'react'
import { Modal } from "bootstrap";
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
import queryKeys from '../../../services/queryKeys';
import {getMediaFileList, templateMediaSet} from '../../../services/services';

export default function UploadModal({productId, selectedSectionDetails}) {

    const queryClient = useQueryClient()
    
    const [selectedFile, setSelectedFile] = useState('')

    const handleSelectedFile = (file_uid) => {
        // if(selectedFile.length && selectedFile.includes(file_uid)){
        //     let indexOfItem = selectedFile.indexOf(file_uid)
        //     let oldFiles = [...selectedFile]
        //     oldFiles.splice(indexOfItem, 1)
        //     setSelectedFile(oldFiles)
        // }else{
        //     setSelectedFile(prev => [...prev, file_uid])
        // }
        setSelectedFile(file_uid)
    }

    const modalRef = useRef(null)

    const dismissModal = () => {
        const body = document.querySelector('body')
        body.removeAttribute('style')
        // body.classList.toggle('modal-open')

        const modalBackdrop = document.querySelectorAll('.modal-backdrop')
        modalBackdrop.forEach(item => {
            if (item) {
                item.remove();
            }
        })
        
        const modal = Modal.getInstance(modalRef.current);
        modal && modal.hide();
    };

    const changeTemplateMediaSet = useMutation({
        mutationFn: (fields) => {
            if(!fields.file_uid){
                throw({message: 'Please select a file first!'})
            }
            return templateMediaSet(fields)
            },
        onSuccess: (res) => {
            // console.log('res', res.data)
            if(res.data.resultCode != '0'){
                throw({message: res?.data?.resultDescription})
            }
            setSelectedFile('')
            dismissModal() // to close modal
            queryClient.refetchQueries({
                queryKey: [...queryKeys.myTemplateConfig],
                // type: 'active',
                // exact: true,
            })
        },
        onSettled: () => {
            setTimeout(()=>{
                changeTemplateMediaSet.reset()
            }, 3000)
        }
    })

    const handleUpload = () => {
        let reqData = {
            token: localStorage.getItem("token"), // USER TOKEN
            uid: localStorage.getItem("uid"), // USER UID
            product_id: productId,
            file_uid: selectedFile,
            image_id: selectedSectionDetails?.id
        };
        // console.log('reqData', reqData)
        changeTemplateMediaSet.mutate(reqData)
    }

    const {data, isFetching, isError, error} = useQuery({
        queryKey: queryKeys.my_files,
        queryFn: () => {
            let reqData = {
                token: localStorage.getItem('token'), // USER TOKEN
                uid: localStorage.getItem('uid') // USER UID
            }
            return getMediaFileList(reqData)
        }
    })

    const mediaFileList = data?.data
    // console.log('mediaFileList', mediaFileList) //file_list

  return (
    <>
        {/* Vertical Center Modal */}
        <div ref={modalRef} className="modal fade" id="verticalCenter" tabIndex="-1" role="dialog" aria-hidden="false">
            <div className="modal-50 modal-dialog modal-dialog-centered modal-50" role="document">
                <div className="modal-content">
                    <div className="modal-header">
                        <h5 className="modal-title" style={{fontSize: '18px'}} id="verticalCenterTitle">Select New Picture</h5>
                        <button type="button" className="close" data-bs-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div className="modal-body">
                        {isFetching ? 
                            <>
                                <div className="col-12">
                                    <p className='text-mute'>Loading...</p>
                                </div>
                            </>
                            : isError ?
                            <div className="col-12">
                                <p className='text-danger'>{error?.message}</p>
                            </div>
                            :
                            <div className='row g-5 justify-content-center'>
                                {mediaFileList?.file_list?.length ?
                                <>
                                {mediaFileList?.file_list?.map(item => {
                                    const file_url = (mediaFileList?.media_server + "/" + item?.file_group + "/" + item?.file_uid + "/" + item.filename).toLowerCase();
                                    return(
                                        <div onClick={()=>handleSelectedFile(item?.file_uid)} className={`p-3 text-center col-4`} style={{cursor: 'pointer'}}>
                                            <div className={`p-3 ${(selectedFile == item?.file_uid) && 'bg-light'}`} style={{Height: '250px'}}>
                                                <img key={item?.file_uid} className="img-fluid" style={{}} src={file_url} alt='file-image' />
                                            </div>
                                        </div>
                                    )
                                    }) 
                                }
                                </>
                                :
                                <p>No File(s) found!</p>
                                }
                            </div>
                        }
                        {changeTemplateMediaSet.error &&
                        <>
                            <div className="col-12">
                            <p className='text-danger'>{changeTemplateMediaSet.error.message}</p>
                        </div>
                        </>
                        }
                        {changeTemplateMediaSet.isSuccess &&
                        <>
                            <div className="col-12">
                                <p className='text-success'>{'subscription is successful'}</p>
                            </div>
                        </>
                        }

                    </div>
                    <div className="modal-footer">
                        <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                        {selectedFile &&
                            <button type="button" className="btn btn-primary" disabled={changeTemplateMediaSet?.isPending || changeTemplateMediaSet?.isSuccess} onClick={handleUpload}>{changeTemplateMediaSet?.isPending ? 'Applying...' : changeTemplateMediaSet?.isSuccess ? 'Applied' : 'Apply'}</button>
                        }
                    </div>
                </div>
            </div>
        </div>
        {/* END of Vertical Center Modal */}
    </>
  )
}
