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, getTemplateConfig, uploadFile} from '../../../services/services';

export default function UploadModal() {

    const [selectedFiles, setSelectedFiles] = useState([])

    const handleSelectedFiles = (file_uid) => {
        if(selectedFiles.length && selectedFiles.includes(file_uid)){
            let indexOfItem = selectedFiles.indexOf(file_uid)
            let oldFiles = [...selectedFiles]
            oldFiles.splice(indexOfItem, 1)
            setSelectedFiles(oldFiles)
        }else{
            setSelectedFiles(prev => [...prev, 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 uploadFileMutation = useMutation({
        mutationFn: (fields) => {
            if(!fields.file){
                throw({message: 'Please select a file first!'})
            }
            // return uploadFile(fields)
            // remember to close the modal
            dismissModal()
            setTimeout(()=>{
                uploadFileMutation.reset()
            }, 3000)
        },
        onSuccess: (res) => {
            // console.log('res', res.data)
            // if(res.data.resultCode != '0' || !res?.data?.pending_uid){
            //     throw({message: res?.data?.resultDescription})
            // }
            // setSelectedFile({id: '', img: ''})
            // queryClient.refetchQueries({
            //     queryKey: [...queryKeys.my_files],
            //     type: 'active',
            //     exact: true,
            // })
        },
        onSettled: () => {
            setTimeout(()=>{
                uploadFileMutation.reset()
            }, 3000)
        }
    })

    const handleUpload = () => {
        let reqData = {
            token: localStorage.getItem("token"), // USER TOKEN
            member_uid: localStorage.getItem("uid"), // USER UID
            // file: selectedFile?.img
        };
        uploadFileMutation.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={()=>handleSelectedFiles(item?.file_uid)} className={`p-3 text-center col-4`} style={{cursor: 'pointer'}}>
                                            <div className={`p-3 ${selectedFiles.includes(item?.file_uid) && 'bg-light'}`}>
                                                <img key={item?.file_uid} className="img-fluid" src={file_url} alt='file-image' />
                                            </div>
                                        </div>
                                    )
                                    }) 
                                }
                                </>
                                :
                                <p>No File(s) found!</p>
                                }
                            </div>
                        }
                        {/* <div style={{fontSize: '18px'}} className="" dangerouslySetInnerHTML={{__html: saleText}}/> */}
                        {/* {mutation.error &&
                        <>
                            <div className="col-12">
                            <p className='text-danger'>{mutation.error.message}</p>
                        </div>
                        </>
                        }
                            {mutation.isSuccess &&
                        <>
                            <div className="col-12">
                                <p className='text-success'>{'subscription is successful'}</p>
                            </div>
                        </>
                        } */}

                        {/* {requestStatus.message && (
                        <div className="col-12">
                            <p className={`p-2 text-center ${requestStatus.status ? 'text-success' : 'text-danger'}`}>{requestStatus.message}</p>
                        </div>
                        )} */}

                    </div>
                    <div className="modal-footer">
                        <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                        {selectedFiles.length > 0 &&
                            <button type="button" className="btn btn-primary" disabled={uploadFileMutation?.isPending || uploadFileMutation?.isSuccess} onClick={handleUpload}>{uploadFileMutation?.isPending ? 'Upload...' : uploadFileMutation?.isSuccess ? 'Uploaded' : 'Upload'}</button>
                        }
                    </div>
                </div>
            </div>
        </div>
        {/* END of Vertical Center Modal */}
    </>
  )
}
