"use client"
import React from 'react';
import Image from 'next/image'
import './style.css'
import Addfile from './addFile'
import Addfolder from './addFolder'
import {uploadFile, getFile, deleteFile, createFolder, deleteFolder,starFile} from "@/app/util/db";
import {usePathname} from 'next/navigation'
import {toast} from 'react-hot-toast';
import 'react-tooltip/dist/react-tooltip.css'
import Loading from './loading'
function breakStringIntoArrays(str, arrayLength) {
    let result = [];
    for (let i = 0; i < str.length; i += arrayLength) {
        result.push(str.slice(i, i + arrayLength));
    }
    return result;
}
const userId = localStorage.getItem('my-drive-user');
export default function File(prop) {

    const pathname = usePathname()
    const [modalIsOpenFile,
        setIsOpenFile] = React.useState(false);
    const [modalIsOpenFolder,
        setIsOpenFolder] = React.useState(false);
    const [fileList,
        setfileList] = React.useState({})
    const [folderList,
        setfolderList] = React.useState({})
    const [tempfileList,
        tempsetfileList] = React.useState({})
    const fileSubmit = (file, name, type, size) => {
        setIsOpenFile(false)
        prop.close(false)
        const uploadfilefn = new Promise(async(resolve, reject) => {
            var regex = new RegExp(`^data:${type.split('/')[0]}\/\\w+;base64,`);
            var blogStrong = breakStringIntoArrays(file.replace(regex, ''), 1040080)
            for (let i = 0; i <= blogStrong.length; i++) {
                try {
                    let pushData = true
                    if (i === blogStrong.length) 
                        pushData = false
                    await uploadFile(userId, blogStrong[i], name, type, size, pathname, pushData).then((data) => {
                        if (!data) 
                            return 0
                        setfileList((prevFileList) => ({
                            ...prevFileList,
                            [
                                Object
                                    .values(fileList)
                                    .length
                            ]: data
                        }));
                        setFilenotFound(false)
                        resolve(data.FILENAME)
                    }).catch(err => {
                        reject(err.message)
                    })
                } catch (e) {
                    reject('Server Error')
                }
            }
        })

        toast.promise(uploadfilefn, {
            loading: `Uploading ${name}..`,
            success: (data) => `${data} Uploaded 👌`,
            error: (err) => `${err}`
        })
    }

    const getAllFiles = async e => {

        const fetchFile = new Promise(async(resolve, reject) => {
            await getFile(userId, pathname).then(data => {

                setfileList({
                    ...data.file
                })
                setfolderList({
                    ...data.folder
                })
                setTimeout(() => {
                    document
                        .getElementById('filecontentloading')
                        .style
                        .display = 'none'
                    document
                        .getElementById('allFileContent')
                        .style
                        .display = 'block'
                    // if (data.length == 0)     prop.folder(true) else     prop.folder(false)
                }, 0);
                if (data.folder.length == 0 && data.file.length == 0) 
                    setFilenotFound(true)
                resolve(" ")
            }).catch(err => {
                console.log(err.message)
                reject(err.message)
            })
        })
        toast.promise(fetchFile, {
            loading: 'Downloading File..',
            success: (data) => `Files Fetched 👌`,
            error: (err) => `${err}`
        })
    }
    const deletefileName = async(FILEID, FILENAME) => {

        const createfilefn = new Promise(async(resolve, reject) => {

            await deleteFile(userId, FILEID, pathname).then(data => {
                setfileList({
                    ...Object
                        .values(fileList)
                        .filter(item => item.FILEID !== FILEID)
                })
                if (Object.values(fileList).length == 1 && (Object.values(folderList).length == 1 || Object.values(folderList).length == 0)) 
                    setFilenotFound(true)
                resolve(FILENAME)
            }).catch(err => reject(""))

        });

        toast.promise(createfilefn, {
            loading: `Deleting ${FILENAME}..`,
            success: (data) => `${data} Deleted 👌`,
            error: "Error deleting file"

        })
    }
    const [ temp,setTemp] = React.useState({})
    const favFile = async (star,fileId)=>{
        await starFile(star,userId,fileId)
        .catch(err => console.log(err.message))
      //  document.getElementById(fileId).innerHTML = "Star"
      setTemp({
        ...Object
            .values(fileList).map(data=>{
                console.log(data)
            })
           
    })
    }
   // console.log(temp)
    React.useEffect(() => {

        getAllFiles()
        // setTimeout(() => {      document.getElementById('filecontentloading') .style
        // .display = 'none'; document.getElementById('allFileContent').style .display
        // = 'block' 0});

    }, [])
    React.useEffect(() => {
        // console.log(prop.openFile)
        if (prop.openFile) 
            setIsOpenFile(true)
    }, [prop.openFile])

    React.useEffect(() => {
        if (prop.openFolder) 
            setIsOpenFolder(true)
    }, [prop.openFolder])
    const createFolderName = e => {
        if (e.trim().length === 0) 
            return
        setIsOpenFolder(false)
        prop.close(false)
        const createfolderfn = new Promise(async(resolve, reject) => {

            await createFolder("CREATEFOLDER", userId, e.trim(), pathname).then(data => {
                try {
                    setfolderList((prevFileList) => ({
                        ...prevFileList,
                        [
                            Object
                                .values(folderList)
                                .length
                        ]: data
                    }));

                } catch (e) {
                    console.log(e)
                }
                setFilenotFound(false)
                resolve("created")
            }).catch(err => {
                reject(err.message)
            })

        });

        toast.promise(createfolderfn, {
            loading: `Creating "${e.trim()}" folder..`,
            success: (data) => `${e.trim()} created 👌`,
            error: (err) => `${err}`
        })
    }
    const deleteFolderName = async(FOLDERID, FOLDERNAME) => {

        const createfolderfn = new Promise(async(resolve, reject) => {

            await deleteFolder(userId, FOLDERID, FOLDERNAME, pathname).then(data => {
                setfolderList({
                    ...Object
                        .values(folderList)
                        .filter(item => item.FOLDERID !== FOLDERID)
                })
                if (Object.values(folderList).length == 1 && (Object.values(fileList).length == 1 || Object.values(fileList).length == 0)) 
                    setFilenotFound(true)

                resolve("")
            }).catch(err => reject(""))

        });

        toast.promise(createfolderfn, {
            loading: `Deleting "${FOLDERNAME}" folder..`,
            success: (data) => `${FOLDERNAME} Deleted 👌`,
            error: "Error deleting folder"

        })
    }
    // <option value="0">By Date (Old to new)</option> <option value="1">By Date
    // (New to Old)</option> <option value="2">By Size (High to Low)</option>
    // <option value="3">By Size (Low to High)</option>
    const onchangeSortSelect = e => {
        
        // if (e === "v0") 
        //     console.log(e)
        if (e === "na") 
            return
        if (e === "v0") 
        setfileList({
            ...Object.values(fileList).sort((a,b) =>  a.DATE - b.DATE)
        })
        else if (e === "v1") 
        setfileList({
            ...Object.values(fileList).sort((a,b) =>  b.DATE - a.DATE)
        })
        else if (e === "v2") 
        setfileList({
            ...Object.values(fileList).sort((a,b) =>  b.SIZE - a.SIZE)
        })
        else if (e === "v3") 
        setfileList({
            ...Object.values(fileList).sort((a,b) =>  a.SIZE - b.SIZE)
        })
    }
   
    const [fileNotFound,
        setFilenotFound] = React.useState(false)
    const [showFileOption,
        setShowFileOption] = React.useState('')
    const [showFolderOption,
        setShowFolderOption] = React.useState('')
    return (
        <div>
            <Addfolder
                addfoldermodalopen={modalIsOpenFolder}
                addfoldermodalclose={e => {
                setIsOpenFolder(false);
                prop.close(false)
            }}
                folder={createFolderName}/>
            <Addfile
                addfilemodalopen={modalIsOpenFile}
                addfilemodalclose={e => {
                setIsOpenFile(false);
                prop.close(false)
            }}
                submit={(file, name, type, size) => fileSubmit(file, name, type, size)}/>
            <div id="filecontentloading">
                <Loading/>
            </div>
            <div className='file w-full ' id="allFileContent">
                {fileNotFound
                    ? <div className='text-center sm:mt-16 mt-36 animate__animated animate__zoomIn'>
                            <img
                                src='/image/undraw_upload_re_pasx.svg'
                                className='sm:w-3/12 w-6/12 mx-auto hover:w-4/12 transition-all duration-75'/>
                            <br/>
                            <p className='font-extrabold'>UPLOAD FILE</p>
                        </div>
                    : <div>
                        <h2 className='font-extrabold'>{Object
                                .values(folderList)
                                .length == 0
                                ? ''
                                : 'Folder'}</h2>

                        <div
                            className='folderlist grid grid-cols-2 gap-4 lg:grid-cols-6 sm:grid-cols-3 mt-5 '>

                            {/* <div
                                className='folder-name  h-24  grid grid-cols-3    bg-sky-900 place-content-start p-3 animate__animated animate__zoomIn'>
                                <div className='folderText col-span-3 '>
                                    <p
                                        className="cursor-pointer w-fit"
                                        onClick={e => {
                                        window.location.href = pathname + '/' + data
                                            .FOLDERNAME
                                            .replace(/ /g, '%20')
                                            .replace(/\//g, '-')
                                    }}>ioiuouo</p>

                                </div>
                                <div className='folderIcon1   '>

                                    {showFolderOption != 123
                                        ? <span
                                                className="material-icons ml-2  cursor-pointer font-extrabold"
                                                onClick={e => {
                                                setShowFolderOption(123)
                                            }}>
                                                more_vert
                                            </span>
                                        : <span
                                            className="material-icons ml-2  cursor-pointer font-extrabold"
                                            onClick={e => {
                                            setShowFolderOption('')
                                        }}>
                                            close
                                        </span>}
                                </div>
                                <div
                                    className=' folderIcon1 text-center  folderIcon2 col-span-2'
                                    style={{
                                    "display": showFolderOption != 123
                                        ? "none"
                                        : "block"
                                }}>
                                    <div className=' grid grid-cols-3     '>
                                                <span className="material-icons ml-2  mt-1 place-content-center animate__animated animate__lightSpeedInLeft">
                                                    share
                                                </span>
                                                <span className="material-icons ml-2  mt-1  place-content-center animate__animated animate__lightSpeedInLeft">
                                                    star
                                                </span>
                                                <span
                                                    class="material-icons  ml-2  mt-1 place-content-center cursor-pointer animate__animated animate__lightSpeedInLeft"
                                                    onClick={e => deleteFolderName(data.FOLDERID, data.FOLDERNAME)}>
                                                    delete
                                                </span>
                                                </div>
                                </div>

                            </div> */}

                            {Object.values(folderList) && Object
                                .values(folderList)
                                .map((data, index) => {
                                    return (
                                        <div
                                            className='folder-name  h-24  grid grid-cols-3    bg-sky-900 place-content-start p-3 animate__animated animate__zoomIn'>
                                            <div className='folderText col-span-3 '>
                                                <p
                                                    className="cursor-pointer w-fit"
                                                    onClick={e => {
                                                    window.location.href = pathname + '/' + data
                                                        .FOLDERNAME
                                                        .replace(/ /g, '%20')
                                                        .replace(/\//g, '-')
                                                }}>{data
                                                        .FOLDERNAME
                                                        .replace(/%20/g, ' ')}</p>
                                                {/* <p>234 Files</p> */}
                                            </div>
                                            <div className='folderIcon1   '>

                                                {showFolderOption != data.FOLDERID
                                                    ? <span
                                                            className="material-icons ml-2  cursor-pointer font-extrabold"
                                                            onClick={e => {
                                                            setShowFolderOption(data.FOLDERID)
                                                        }}>
                                                            more_vert
                                                        </span>
                                                    : <span
                                                        className="material-icons ml-2  cursor-pointer font-extrabold"
                                                        onClick={e => {
                                                        setShowFolderOption('')
                                                    }}>
                                                        close
                                                    </span>}
                                            </div>
                                            <div
                                                className=' folderIcon1 text-center  folderIcon2 col-span-2'
                                                style={{
                                                "display": showFolderOption != data.FOLDERID
                                                    ? "none"
                                                    : "block"
                                            }}>
                                                <div className=' grid grid-cols-3     '>
                                                    <span
                                                        className="material-icons ml-2  mt-1 place-content-center animate__animated animate__lightSpeedInLeft">
                                                        share
                                                    </span>
                                                    <span
                                                        className="material-icons ml-2  mt-1  place-content-center animate__animated animate__lightSpeedInLeft">
                                                        star
                                                    </span>
                                                    <span
                                                        class="material-icons  ml-2  mt-1 place-content-center cursor-pointer animate__animated animate__lightSpeedInLeft"
                                                        onClick={e => deleteFolderName(data.FOLDERID, data.FOLDERNAME)}>
                                                        delete
                                                    </span>
                                                </div>

                                            </div>
                                        </div>
                                    )
                                })}

                        </div>
                        <br/> 
                        {/* <select
                            id="countries" onChange={e=>onchangeSortSelect(e.target.value)}
                            class="float-right bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-2/12 p-1 mr-10 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
                            <option selected value="na">Sort File</option>
                            <option value="v0">By Date (Old to new)</option>
                            <option value="v1">By Date (New to Old)</option>
                            <option value="v2">By Size (High to Low)</option>
                            <option value="v3">By Size (Low to High)</option>
                        </select> */}
                    
                        <h2 className='font-extrabold flex'>{Object
                                .values(fileList)
                                .length == 0
                                ? ''
                                : 'File'}

                        </h2>

                        <div
                            className='filelist grid grid-cols-2 gap-4 lg:grid-cols-6 sm:grid-cols-3 mt-5  '>
                            {/* <div>
                                        <div
                                            className='file-name p-3 grid  grid-cols-4 bg-white h-44 animate__animated animate__zoomIn'>

                                            <div
                                                className='col-span-4 h-24 border flex w-fulljustify-center bg-white  items-center rounded-md overflow-hidden'>
                                                   jhkhk
                                            </div>
                                            <div className='fileName col-span-4 text-center '>

                                            <p className='font-extrabold text-xs'>hjk</p>
                                                <br/>
                                            </div>
                                            <div className='text-center border ingIOcon1 pt-1 bg-slate-100'>
                                                {showFileOption != 123 ?
                                                <span className="material-icons" onClick={e=>{setShowFileOption(123)}}>
                                                more_vert
                                                </span> :
                                                <span className="material-icons" onClick={e=>{setShowFileOption('')}}>
                                                close
                                                </span> }

                                            </div>
                                            <div className='text-center pt-1 border ingIOcon col-span-3 '
                                            style={{"display" : showFileOption != 123 ? "none" : "block",}}
                                            >
                                                <div className=' grid grid-cols-3     '>
                                                <span className="material-icons ml-2  mt-1 place-content-center animate__animated animate__lightSpeedInLeft">
                                                    share
                                                </span>
                                                <span className="material-icons ml-2  mt-1  place-content-center animate__animated animate__lightSpeedInLeft">
                                                    star
                                                </span>
                                                <span
                                                    class="material-icons  ml-2  mt-1 place-content-center cursor-pointer animate__animated animate__lightSpeedInLeft"
                                                    onClick={e => deletefileName(data.FILEID, data.FILENAME)}>
                                                    delete
                                                </span>
                                                </div>

                                            </div>

                                        </div>
                                    </div> */}

                            {Object.values(fileList) && Object
                                .values(fileList)
                                .map((data, index) => {
                                    return (
                                        <div>
                                            <div
                                                className='file-name p-3 grid  grid-cols-4 bg-white h-44 animate__animated animate__zoomIn'>

                                                <div
                                                    className='col-span-4 h-24 border cursor-pointer flex w-full justify-center bg-white  items-center rounded-md overflow-hidden'>
                                                    {/* */}
                                                    {data
                                                        .FILETYPE
                                                        .split('/')[0] == 'text'
                                                        ? <div className='flex justify-center items-center'>
                                                                <span className="material-icons description">description</span>
                                                            </div>
                                                        : data
                                                            .FILETYPE
                                                            .split('/')[0] == 'application'
                                                            ? <div>
                                                                    {data
                                                                        .FILETYPE
                                                                        .split('/')[1]
                                                                        .includes('.document')
                                                                        ? <img src='/image/icons8-microsoft-word.svg' className='w-5/12 mx-auto'/>
                                                                        : data
                                                                            .FILETYPE
                                                                            .split('/')[1]
                                                                            .includes('.presentation')
                                                                            ? <img src='/image/icons8-microsoft-powerpoint.svg' className='w-5/12 mx-auto'/>
                                                                            : <div className='flex justify-center items-center'>
                                                                            <span className="material-icons description">picture_as_pdf</span>
                                                                        </div>}

                                                                </div>
                                                            : data
                                                                .FILETYPE
                                                                .split('/')[0] == 'video'
                                                                ? <div className='videoDiv'>
                                                                        <span className="material-icons">play_circle</span>
                                                                        <video width="200" preload="metadata">
                                                                            <source src={process.env.SERVERPATH + '/' + data.FILEPATH} type={"video/mp4"}/>
                                                                            Your browser does not support the video tag.
                                                                        </video>
                                                                    </div>
                                                                :
                                                                data
                                                                .FILETYPE
                                                                .split('/')[0] == 'image'? 
                                                                <img
                                                                    src={process.env.SERVERPATH + '/' + data.FILEPATH}
                                                                    className='w-10/12 mx-auto'/> :<img src='/image/icons8-file-100.png' className='w-5/12 mx-auto'/>}
                                                </div>
                                                <div className='fileName col-span-4 text-center '>

                                                    <p className='font-extrabold text-xs'>{data.FILENAME}</p>
                                                    <br/>
                                                </div>
                                                <div className='text-center border ingIOcon1 pt-1 bg-slate-100'>
                                                    {showFileOption != data.FILEID
                                                        ? <span
                                                                className="material-icons"
                                                                onClick={e => {
                                                                setShowFileOption(data.FILEID)
                                                            }}>
                                                                more_vert
                                                            </span>
                                                        : <span
                                                            className="material-icons"
                                                            onClick={e => {
                                                            setShowFileOption('')
                                                        }}>
                                                            close
                                                        </span>}

                                                </div>
                                                <div
                                                    className='text-center pt-1 border ingIOcon col-span-3 animate__animated animate__fadeIn'
                                                    style={{
                                                    "display": showFileOption != data.FILEID
                                                        ? "none"
                                                        : "block"
                                                }}>
                                                    <div className=' grid grid-cols-3     '>
                                                        <span
                                                            className="material-icons ml-2  mt-1 place-content-center animate__animated animate__lightSpeedInLeft">
                                                            share
                                                        </span>
                                                        <span onClick={e=>favFile(!data.STAR,data.FILEID)}
                                                            className="material-icons ml-2  mt-1  place-content-center animate__animated animate__lightSpeedInLeft"
                                                             id={data.FILEID}>
                                                           {!data.STAR ? "star_outline" : "star" }
                                                        </span>
                                                        <span
                                                            class="material-icons  ml-2  mt-1 place-content-center cursor-pointer animate__animated animate__lightSpeedInLeft"
                                                            onClick={e => deletefileName(data.FILEID, data.FILENAME)}>
                                                            delete
                                                        </span>
                                                    </div>
                                                </div>

                                            </div>
                                        </div>

                                    )
                                })}
                        </div>
                    </div>
}
            </div>
        </div>

    )
}
