import React, { Component } from 'react';
import { TextField, Divider, Typography, Checkbox, withStyles, Collapse, MuiThemeProvider } from '@material-ui/core';
import api from '../../../api';
import AddIcon from '@material-ui/icons/Add';
import RemoveIcon from '@material-ui/icons/Remove';
import { DateTimePicker, KeyboardDatePicker, DatePicker} from "@material-ui/pickers";
import format from "date-fns/format";
import localeID from "date-fns/locale/id"

const CustomCheckbox = withStyles({
    root: {
      color: '#51c6ea',
      '&$checked': {
        color: '#51c6ea',
      },
      padding: 5
    },
    checked: {},
  })((props) => <Checkbox color="default" {...props} />);

export default class AddRole extends Component {
    
    constructor(props) {
        super(props)
        this.state = {
            paramsId: this.props.data,
            tempData: null,
            menuData: null,
            privileges: [],
            checked: false,
            selectedIndex: 0,
            roleName: '',
            startDate: null,
            endDate: null,
            date: new Date()
        }
    }

    handleChecked() {
        this.setState({checked: !this.state.checked})
    }
    
    componentDidMount() {
        this.getMenu()
    }

    handleChange(e, type) {
        let data = this.state
        let isDate = type !== ''? true : false
        if (isDate && type == 'start_date') {
            this.setState({...data, startDate : format(e, 'yyyy-MM-dd')})
        } else if (isDate && type == 'end_date') {
            this.setState({...data, endDate : format(e, 'yyyy-MM-dd')})
        } else {
            this.setState({...data, [e.target.name] :  e.target.value})
        }
        
    }

    updateRole() {
        // let startDate = format(this.state.tempData.start_date, 'yyyy-MM-dd')
        // let endDate = format(this.state.tempData.end_date, 'yyyy-MM-dd')
        let payload = {
            "role_name": this.state.roleName,
            "start_date": this.state.startDate,
            "end_date": this.state.endDate,
            "privileges": this.state.privileges
        }
        // console.log(payload)
        api.create().addRole(payload).then((response) => {
            console.log(response)
            if (response.data.status == 'success') {
                this.props.refresh()
                this.props.onClickClose()
            } else {
                alert(response.data.message)
            }
        })
    }

    getMenu() {
        api.create().getMenu().then((response) => {
            if (response.data.status == 'success') {
                this.setState({menuData: response.data.data})
            } else {
                alert(response.data.message)
            }
        })
    }

    handleItemChecked(item) {
        let indexID = this.state.privileges.findIndex((val) => val.menu_id == item.menu_id)
        return indexID == -1? false : true
    }

    handleItemClick(item) {
        let indexID = this.state.privileges.findIndex((val) => val.menu_id == item.menu_id)
        let privileges = this.state.privileges
        if (indexID == -1) {
            privileges.push({
                menu_id: item.menu_id,
                button_id: [1,2,3]
            })
        } else {
            privileges.splice(indexID,1)
        }
        this.setState({privileges})
    }

    handleSubItemChecked(item, index) {
        let indexID = this.state.privileges.findIndex((val) => val.menu_id == item.menu_id)
        let value = false
        if (indexID == -1) {
            value = false
        } else {
            let arrayButton = this.state.privileges[indexID].button_id
            // console.log(arrayButton)
            let indexButtonID = this.state.privileges[indexID].button_id.findIndex((val) => val == index)
            // console.log(indexButtonID)
            if (indexButtonID == -1) {
                value = false
            } else {
                value = true
            }
        }
        return indexID == -1? value : value
    }

    handleSubItemClick(item, index) {
        let indexID = this.state.privileges.findIndex((val) => val.menu_id == item.menu_id)
        let indexButtonID = this.state.privileges[indexID].button_id.findIndex((val) => val == index)
        let privileges = this.state.privileges
        let button_id = privileges[indexID].button_id
        if (indexButtonID == -1) {
            button_id.push(index)
        } else {
            button_id.splice(indexButtonID,1)
        }
        privileges[indexID].button_id = button_id
        if (button_id.length == 0) {
            privileges.splice(indexID,1)
        }
        this.setState({privileges})
    }

    handleDate(item) {
        let value = format(item, 'dd MMMM yyyy')
        return value
    }

    render() {
        return (
            <div className="test app-popup-show">
                <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                    <div className="popup-panel grid grid-2x" style={{ backgroundColor: '#51c6ea', height: 64, borderTopRightRadius: 8, borderTopLeftRadius: 8 }}>
                        <div className="col-1" style={{ maxWidth: "inherit", display: 'flex', alignItems: 'center' }}>
                            <div className="popup-title">
                                <span style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>Tambah Data</span>
                            </div>
                        </div>
                        <div className="col-2 content-right" style={{ maxWidth: "inherit", alignSelf: 'center' }}>
                            <button
                                type="button"
                                className="btn btn-circle btn-white"
                                onClick={() => this.props.onClickClose()}
                            >
                                <i className="fa fa-lg fa-times" style={{ color: 'white' }} />
                            </button>
                        </div>
                    </div>

                    <div className="grid grid-2x grid-mobile-none gap-15px" style={{ padding: 20 }}>
                        <div className="column-1">
                            <div className="margin-bottom-20px">
                                <TextField
                                    style={{ width: '100%' }}
                                    id="id"
                                    label="ID"
                                    disabled
                                    // id="outlined-read-only-input"
                                    variant="filled"
                                    value={'-'}
                                    onChange={(e) => null}
                                >
                                    {/* {periode.map((option) => (
                                        <MenuItem key={option.value} value={option.value}>
                                            {option.label}
                                        </MenuItem>
                                    ))} */}
                                </TextField>
                            </div>
                        </div>

                        <div className="column-2">
                            <div className="margin-bottom-20px">
                                <TextField
                                style={{ width: '100%' , marginTop: 7}}
                                id="userRole"
                                name="roleName"
                                label="User Role"
                                value={this.state.roleName}
                                onChange={(e) => this.handleChange(e, '')}
                                // defaultValue="Default Value"
                                // helperText="Some important text"
                                />
                            </div>
                        </div>
                    </div>

                    <div className="grid grid-2x grid-mobile-none gap-15px" style={{ paddingLeft: 20, paddingRight: 20 }}>
                        <div className="column-1">
                            <div className="margin-bottom-20px">
                                <DatePicker
                                margin="normal"
                                id="startDate"
                                label="Berlaku Mulai"
                                format="dd MMMM yyyy"
                                value={this.state.startDate}
                                onChange={(e) => this.handleChange(e, 'start_date')}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                                
                                style={{padding: 0, margin: 0, width: '100%'}}
                                />
                            </div>
                        </div>

                        <div className="column-2">
                            <div className="margin-bottom-20px">
                                <DatePicker
                                margin="normal"
                                id="endDate"
                                label="Berlaku Hingga"
                                format="dd MMMM yyyy"
                                value={this.state.endDate}
                                onChange={(e) => this.handleChange(e, 'end_date')}
                                minDate={this.state.startDate}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                                
                                style={{padding: 0, margin: 0, width: '100%'}}
                                />
                            </div>
                        </div>
                    </div>

                    <div className="grid grid-2x grid-mobile-none gap-15px" style={{ paddingLeft: 20, paddingRight: 20 }}>
                        <div className="column-1">
                            <div className="margin-bottom-20px">
                                <TextField
                                    style={{ width: '100%' }}
                                    id="status"
                                    label="Status"
                                    disabled
                                    // id="outlined-read-only-input"
                                    variant="filled"
                                    value={'Aktif'}
                                >
                                    {/* {periode.map((option) => (
                                        <MenuItem key={option.value} value={option.value}>
                                            {option.label}
                                        </MenuItem>
                                    ))} */}
                                </TextField>
                            </div>
                        </div>
                    </div>
                    <div style={{flexDirection:'column', display: 'flex', paddingLeft: 20, paddingRight: 20 }}>
                        <Typography style={{fontSize: 12}}>{`Dibuat  : ${format(this.state.date, 'dd MMMM yyyy', {locale: localeID})}`}</Typography>
                        {/* <Typography style={{fontSize: 12}}>{`Diubah: ${this.state.tempData == null? '' : this.state.tempData.updated}`}</Typography> */}
                    </div>
                    <Divider style={{margin: 20}}/>
                    <div style={{paddingLeft: 20, paddingRight: 20}}>
                        <h5>Hak Akses</h5>
                        <div className="grid grid-2x grid-mobile-none gap-15px padding-top-5px padding-bottom-5px padding-left-10px padding-right-10px " style={{backgroundColor: '#4b4b4b'}}>
                            <div className="column-1">
                                <Typography style={{fontSize: 12, color: 'white'}}>Otorisasi Modul</Typography>
                            </div>
                            <div className="column-2 grid grid-3x content-center grid-mobile-none gap-15px">
                                <div className="column-1">
                                    <Typography style={{fontSize: 12, color: 'white'}}>Lihat</Typography>
                                </div>
                                <div className="column-2">
                                    <Typography style={{fontSize: 12, color: 'white'}}>Tambah</Typography>
                                </div>
                                <div className="column 3">
                                    <Typography style={{fontSize: 12, color: 'white'}}>Ubah</Typography>
                                </div>
                            </div>
                        </div>
                        
                        <div style={{height: '25vh', overflow: 'scroll'}}>
                            {this.state.menuData !== null && this.state.menuData.map((item,index) => {
                                return (
                                    <div>
                                        <div className="grid grid-2x grid-mobile-none gap-15px padding-left-10px padding-right-10px">
                                            <div className="column-1" style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start'}}>
                                                {item.sub_menu.length > 0 && <span onClick={() => this.setState({selectedIndex: index == this.state.selectedIndex? 0 : index})} style={{marginLeft: 7, marginRight: 2}}>
                                                    {index == this.state.selectedIndex? <RemoveIcon color={'action'} fontSize={'small'}/> : <AddIcon color={'action'} fontSize={'small'}/>}    
                                                </span>}
                                                <span>
                                                <CustomCheckbox
                                                    checked={this.handleItemChecked(item)}
                                                    onChange={() => this.handleItemClick(item)}
                                                />
                                                </span>
                                                <Typography style={{fontSize: 12, marginLeft: 5}}>{item.menu_name}</Typography>
                                            </div>
                                            <div className="column-2 grid grid-3x content-center grid-mobile-none gap-15px">
                                                <div className="column-1">
                                                    <CustomCheckbox
                                                        disabled={!this.handleItemChecked(item)}
                                                        checked={this.handleSubItemChecked(item, 1)}
                                                        onChange={() => this.handleSubItemClick(item,1)}
                                                    />
                                                </div>
                                                <div className="column-2">
                                                    <CustomCheckbox
                                                        // disabled
                                                        disabled={!this.handleItemChecked(item)}
                                                        checked={this.handleSubItemChecked(item, 2)}
                                                        onChange={() => this.handleSubItemClick(item,2)}
                                                    />
                                                </div>
                                                <div className="column 3">
                                                    <CustomCheckbox
                                                        // disabled
                                                        disabled={!this.handleItemChecked(item)}
                                                        checked={this.handleSubItemChecked(item, 3)}
                                                        onChange={() => this.handleSubItemClick(item,3)}
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                        {item.sub_menu.length > 0 && item.sub_menu.map((items,indexs) => {
                                            return(
                                                <Collapse in={index == this.state.selectedIndex} timeout="auto" unmountOnExit>
                                                    <div className="grid grid-2x grid-mobile-none gap-15px padding-left-10px padding-right-10px">
                                                        <div className="column-1" style={{display: 'flex', flexDirection: 'row', alignItems: 'center', paddingLeft: 50}}>
                                                            <CustomCheckbox
                                                                checked={this.handleItemChecked(items)}
                                                                onChange={() => this.handleItemClick(items)}
                                                            />
                                                            <Typography style={{fontSize: 12, maxWidth: '100%', marginLeft: 5}}>{items.menu_name}</Typography>
                                                        </div>
                                                        <div className="column-2 grid grid-3x content-center grid-mobile-none gap-15px">
                                                            <div className="column-1">
                                                                <CustomCheckbox
                                                                    disabled={!this.handleItemChecked(items)}
                                                                    checked={this.handleSubItemChecked(items, 1)}
                                                                    onChange={() => this.handleSubItemClick(items,1)}
                                                                />
                                                            </div>
                                                            <div className="column-2">
                                                                <CustomCheckbox
                                                                    disabled={!this.handleItemChecked(items)}
                                                                    checked={this.handleSubItemChecked(items, 2)}
                                                                    onChange={() => this.handleSubItemClick(items,2)}
                                                                />
                                                            </div>
                                                            <div className="column 3">
                                                                <CustomCheckbox
                                                                    disabled={!this.handleItemChecked(items)}
                                                                    checked={this.handleSubItemChecked(items, 3)}
                                                                    onChange={() => this.handleSubItemClick(items,3)}
                                                                />
                                                            </div>
                                                        </div>
                                                    </div>
                                                </Collapse>
                                            )
                                        })}
                                    </div>
                                )
                            })}
                        </div>
                        
                    </div>
                    <div className="border-top grid grid-2x" style={{ height: 56, backgroundColor: '#f5f5f5', paddingLeft: 20, paddingRight: 20 }}>
                        <div className="column-1" style={{ alignSelf: 'center' }}>
                            <div onClick={() => this.props.onClickClose()} style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                <span style={{ color: '#354960', fontSize: 11 }}>Batal</span>
                            </div>
                        </div>
                        <div className="column-2" style={{display: 'flex', justifyContent: 'flex-end', alignItems: 'center'}}>
                            <div onClick={() => this.updateRole()}style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                <span style={{ color: '#fff', fontSize: 11 }}>Simpan</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
