import {React, useState} from 'react'
import {SbTitle, SbSub} from './Sb.style'
import { FcFolder, FcOpenedFolder, FcFile } from 'react-icons/fc'
import { AiOutlinePlusSquare, AiOutlineMinusSquare } from 'react-icons/ai'

const SbItem = ({item, openDocCode, updateDocCode}) => {
    const find = (array, openDocCode) => {
        var result;
        array.some(o => result = o.doc_code === openDocCode ? o : find(o.childrens || [], openDocCode));
        return result;
    };
    const collapsedFlag = find(item.childrens, openDocCode) !== undefined;
    // openDocCode === item.doc_code+' '+item.doc_code_name
    const [collapsed, setCollapsed] = useState(collapsedFlag);
    function toggleCollapse() {
        setCollapsed(prevValue => !prevValue);
    }
    function changeOpenDoc(seq){
        const prevOpenDoc = window.document.getElementsByClassName("openDoc")[0];
        prevOpenDoc.className = prevOpenDoc.className.replace('openDoc', '');
        const nextOpenDoc = window.document.getElementById("doc"+seq);
        nextOpenDoc.className = nextOpenDoc.className+' openDoc';
    }

    if(item.group_yn==='Y'){
        const icon1 = collapsed?<AiOutlinePlusSquare />:<AiOutlineMinusSquare />;
        const icon2 = collapsed?<FcOpenedFolder />:<FcFolder />;
        return (
            <div>
                <SbTitle depth={item.doc_level} onClick={toggleCollapse}>{icon1}{icon2}&nbsp;{(item.doc_level === 1?'':item.doc_code)+' '+item.doc_code_name}</SbTitle>
                <SbSub isOpen={collapsed}>
                    {item.childrens.map((child) => (
                        <SbItem item={child} openDocCode={openDocCode} updateDocCode={updateDocCode} />
                    ))}
                </SbSub>
            </div>
        )
    }else{
        const icon = <FcFile />;
        let errorCnt = null;
        if(item.error_cnt != null && item.error_cnt >0){
            errorCnt = <blockquote className="errorCnt">({item.error_cnt})</blockquote>;
        }
        return (
            <SbTitle depth={item.doc_level} id={`doc${item.seq}`} className={item.doc_code === openDocCode?'openDoc':''}>
                <a onClick={()=>{
                    changeOpenDoc(item.seq)
                    updateDocCode(item.doc_code)
                }}>
                    {icon}&nbsp;{(item.doc_level === 1?'':item.doc_code)+' '+item.doc_code_name}
                    {errorCnt}
                </a>
            </SbTitle>
        )
    }

}

export default SbItem