"use client"
import React from 'react';
import Image from 'next/image'
import './style.css'
import Addfolder from './addFolder'
import {createFolder, getFolder, deleteFolder} from "@/app/util/db";
import folderColor from '@/app/helper/folderColor'
import {usePathname} from 'next/navigation'
import {toast} from 'react-hot-toast';
import 'react-tooltip/dist/react-tooltip.css'
import {Tooltip} from 'react-tooltip'
import Loading from './loading'
export default function Folder(prop) {
    const [modalIsOpenFolder,
        setIsOpenFolder] = React.useState(false);
    const pathname = usePathname()
    const [folderList,
        setfolderList] = React.useState({})
    const createFolderName = e => {
        if (e.trim().length === 0) 
            return
        setIsOpenFolder(false)
        prop.close(false)
        const createfolderfn = new Promise(async(resolve, reject) => {

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

                resolve("created")
            }).catch(err => {
                reject(err.message)
            })

        });

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

    const folderlistItem = async e => {
        await getFolder(pathname).then(data => {

            setfolderList({
                ...data
            })

            setTimeout(() => {
                document
                    .getElementById('folderLoading')
                    .style
                    .display = 'none'
                document
                    .getElementById('foldercontent')
                    .style
                    .display = 'block'
                if (data.length == 0) 
                    prop.folder(true)
                else 
                    prop.folder(false)
            }, 0);
        }).catch(err => {
            //alert(err.message)
        })
    }
    const deleteFolderName = async(FOLDERID, FOLDERNAME) => {

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

            await deleteFolder(FOLDERID, FOLDERNAME, pathname).then(data => {
                setfolderList({
                    ...Object
                        .values(folderList)
                        .filter(item => item.FOLDERID !== FOLDERID)
                })
                if (Object.values(folderList).length == 1) 
                    prop.folder(true)

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

        });

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

        })
    }
    React.useEffect(() => {
        setTimeout(() => {
            folderlistItem()
        }, 200);

    }, [])
    React.useEffect(() => {
        if (prop.open) 
            setIsOpenFolder(true)
    }, [prop.open])
    try {
        // console.log(Math.floor(Math.random() * 10))
    } catch {}
    return (

        <div>
            <div id="folderLoading">
                <Loading/>
            </div>
            <div className='folder' id="foldercontent">
                <br/>
                <h2 className='font-extrabold'>{Object
                        .values(folderList)
                        .length == 0
                        ? ''
                        : 'Folder'}</h2>
                <Addfolder
                    open={modalIsOpenFolder}
                    close={e => {
                    setIsOpenFolder(false);
                    prop.close(false)
                }}
                    folder={createFolderName}/>
                <div
                    className='folderlist grid grid-cols-2 gap-4 lg:grid-cols-6 sm:grid-cols-3 mt-5 '>
                    {Object.values(folderList) && Object
                        .values(folderList)
                        .map((data, index) => {
                            return (
                                <div
                                    className='folder-name  h-24  grid grid-cols-6    bg-sky-900 place-content-start p-3 animate__animated animate__zoomIn'>
                                    <div className='folderText col-span-5 '>
                                        <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='folderIcon text-right '>
                                        <span className="material-icons">
                                            share
                                        </span>
                                        <br/>
                                        <br/>
                                        <span
                                            class="material-icons"
                                            onClick={e => deleteFolderName(data.FOLDERID, data.FOLDERNAME)}>
                                            delete
                                        </span>
                                    </div>
                                </div>
                            //         <div             className={'folder-name w-72 h-24  grid grid-cols-3
                            // gap-4  bg-sky-900 place-content-start p-3 cursor-pointer'}> <div
                            // className='folderText col-span-2'> <p>{data.FOLDERNAME.replace(/%20/g, '
                            // ')}</p>             <p>234 Files</p> </div> <div className='folderIcon
                            // text-right'>     <span className="material-icons">         share     </span>
                            // <br/>   <br/> <span class="material-icons">         delete     </span>
                            // </div> </div>
                            )
                        })}

                </div>
            </div>
        </div>

    )
}
