import React from 'react';
import { styled } from '@mui/material/styles';
import Card from '@mui/material/Card';
import { CardActionArea } from '@mui/material';
import Paper from '@mui/material/Paper';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import EditIcon from '@mui/icons-material/Edit';
import ListItemText from '@mui/material/ListItemText';
import IconButton from '@mui/material/IconButton';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import DeleteIcon from '@mui/icons-material/Delete';
import AddIcon from '@mui/icons-material/Add';

import styledComponent from "styled-components";


import CODE from 'constants/code';


const StyledDiv = styledComponent.div`
    .text-item.active {
        background-color: #676767;
    }
`;

function generate(items, element, onClickListner,nameKey,
    idKey) {

    let returnValue = [];
    let nIndex = 0;
    Object.keys(items).forEach(function(key) {


        returnValue = [
            ...returnValue,
            React.cloneElement(element, {
                key,
                'data-key' : key,
                'data-index' : nIndex,
            },
            <Card  className="text-item" sx={{ '&': { boxShadow: 'none' } }} key={key} data-index={nIndex} onClick={(e) => {onClickListner(e, key);}}>
                <CardActionArea sx={{ px: 1 }}>
                    <ListItemText
                        primary={items[key][nameKey]}
                        key={key}
                    />
                </CardActionArea>
            </Card>),
        ];
        nIndex++;
    });
    return returnValue;
}

const Demo = styled('div')(({ theme }) => ({
    backgroundColor: theme.palette.background.paper,
}));

const Item = styled(Paper)(({ theme }) => ({
    backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
    ...theme.typography.body2,
    padding: theme.spacing(1),
    textAlign: 'center',
    color: theme.palette.text.secondary,
}));

function ListCreateUpdateDelete(props) {

    const handleClickCreate = (e) => {
 
        const mode = CODE.MODE_CREATE;

        let paramOrgId = props.itemIndex[props.depthSelectedArrayIndex-1];
        if( props.depthSelectedArrayIndex === 0 ) {
            paramOrgId = "00";
        }
        if( props.depthSelectedArrayIndex !== 0 && props.itemIndex[props.depthSelectedArrayIndex-1] === undefined ) {
            alert('상위 코드를 선택해주세요.');
            props.setIsPopupOpen(false);
            return false;
        }

        props.setCreateOrModifyCondition({mode, paramCodeLevel : props.paramCodeLevel, paramOrgId});
        props.setIsPopupOpen(true);
    };

    const handleClickModify = (e) => {

        const mode = CODE.MODE_MODIFY;

        let paramOrgId = props.itemIndex[props.depthSelectedArrayIndex-1];
        if( props.depthSelectedArrayIndex === 0 ) {
            paramOrgId = "00";
        }        

        const dataKey = e.currentTarget.parentNode.parentNode.parentNode.getAttribute('data-key');
        const target = props.items[dataKey];

        props.setCreateOrModifyCondition({mode, paramCodeLevel : props.paramCodeLevel, paramOrgId, target });
        props.setIsPopupOpen(true);

    };

    const onClickItem = (e, index) => {
        index = Number(index);
        // 기존 active를 모두 해제 한다.
        let siblingEle = e.currentTarget.parentNode.parentNode.firstChild;
        do {
            siblingEle.firstChild.classList.remove('active');
        // eslint-disable-next-line no-cond-assign
        } while (siblingEle = siblingEle.nextSibling);

        e.currentTarget.classList.add('active');
        const myKey = Number(index);
        props.itemIndex[props.depthSelectedArrayIndex] = myKey;
        let forChangeObject = [...props.itemIndex];
        props.setItemIndex(forChangeObject);
    };

    return (
        <StyledDiv>
            <Paper>
                <Typography sx={{ p: 0 }} variant="h6" component="div">
                <Grid container spacing={0} columns={10} sx={{ '&': { backgroundColor: '#333333', height: '56px'}}}>
                    <Grid item xs={6} md={8} >
                        <Item sx={{ px: 0, '&': { boxShadow: 'none', color: '#ffffff', fontWeight: '600', fontSize: '18px', backgroundColor: 'transparent', lineHeight: '40px' }}}>{props.title}</Item>
                    </Grid>
                    <Grid item xs={0} md={2} sx={{ pl: 0, '&': {backgroundColor: 'transparent' }}}>
                        <Item sx={{ p: 0, '&': { boxShadow: 'none', backgroundColor: '#169bd5', borderRadius: '0px'} }}>
                            <IconButton aria-label="add" sx={{ px: 0, borderRadius: '0px', width: '100%', height: '56px'}} onClick={handleClickCreate}>                               
                                <AddIcon sx={{ px: 0, '&': {color: '#ffffff', width: '30px', height: '30px' }}} />
                            </IconButton>
                        </Item>
                    </Grid>                                    
                </Grid>
                </Typography>
                <Demo>
                    <List dense={false} sx={{ px: 0, '&': { minHeight: '315px', height: '615px', overflowY: 'auto'}}}>
                    {generate(
                        props.items,                    
                        <ListItem
                        secondaryAction={
                            <div>                                                
                                <IconButton sx={{ mx: 0 }} edge="start" aria-label="edit" onClick={handleClickModify}>                                                
                                    <EditIcon />
                                </IconButton>
                                <IconButton edge="end" aria-label="delete" onClick={(e)=> {
                                    const dataKey = Number(e.currentTarget.parentNode.parentNode.parentNode.getAttribute('data-key'));

                                    let paramCodeGroup = null;
                                    if( props.depthSelectedArrayIndex > 0 ) {
                                        paramCodeGroup = props.itemIndex[props.depthSelectedArrayIndex-1];
                                    }

                                    props.onClickDeleteItem(e, paramCodeGroup, props.paramCodeLevel, props.depthSelectedArrayIndex, props.items[dataKey]);
                                    }}>                                                
                                    <DeleteIcon />   
                                </IconButton>
                            </div>
                        }
                        >
                        </ListItem>,
                        onClickItem,
                        props.nameKey,
                        props.idKey
                    )}
                    </List>
                </Demo>                
            </Paper>
        </StyledDiv>
        
    );
}

export default ListCreateUpdateDelete;