import React, { Component } from 'react';
import { TextField, Divider, Typography, Checkbox, withStyles, Collapse } from '@material-ui/core';
import api from '../../../api';
import { titleCase } from '../../../library/Utils';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { DatePicker } from '@material-ui/pickers';
import format from "date-fns/format";
import * as R from 'ramda'
import RemoveIcon from '@material-ui/icons/Remove';
import AddIcon from '@material-ui/icons/Add';

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

export default class EditUser extends Component {
    
    constructor(props) {
        super(props)
        this.state = {
            paramsId: this.props.data,
            tempData: null,
            menuData: null,
            checked: false,
            listRole: null,
            role: null,
            company: [],
            listCompany: [],
            selectedIndex: 0,
            errorFullname: false,
            errorEmail: false,
            errorRoleName: false,
            errorStartDate: false,
            errorEndDate: false,
            msgErrorFN: '',
            msgErrorEM: '',
            msgErrorRN: '',
            msgErrorSD: '',
            msgErrorED: '',
        }
    }

    handleChecked() {
        this.setState({checked: !this.state.checked})
    }
    
    componentDidMount() {
        this.getDetailUser()
        this.getRole()
        this.getPerusahaan()
    }

    handleChange(e, type) {
        let data = this.state
        let isDate = type !== '' ? true : false
        if (isDate && type == 'start_date') {
            this.setState({ ...data, tempData: { ...this.state.tempData, start_date: format(e, 'yyyy-MM-dd'), end_date: null },
                errorRoleName: false,
                errorStartDate: false,
                errorEndDate: false,
                msgErrorRN: '',
                msgErrorSD: '',
                msgErrorED: '',
            })
        } else if (isDate && type == 'end_date') {
            this.setState({ ...data, tempData: { ...this.state.tempData, end_date: format(e, 'yyyy-MM-dd') },
                errorRoleName: false,
                errorStartDate: false,
                errorEndDate: false,
                msgErrorRN: '',
                msgErrorSD: '',
                msgErrorED: '',
            })
        } else {
            this.setState({ ...data, tempData: { ...this.state.tempData, [e.target.name]: e.target.value }, 
                errorRoleName: false,
                errorStartDate: false,
                errorEndDate: false,
                msgErrorRN: '',
                msgErrorSD: '',
                msgErrorED: '', 
            })
        }
    }

    getDetailUser() {
        api.create().getDetailUser(this.state.paramsId).then((response) => {
            if (response.data.status == 'success') {
                this.setState({tempData: response.data.data, company: response.data.data.company})
                console.log(response.data.data)
            } else {
                alert(response.data.message)
            }
        })
    }

    validasi() {
        this.updateUser()
    }

    updateUser() {
        let payload = {
            "user_id": this.state.tempData.user_id,
            "role_id": this.state.role.role_id,
            "email": this.state.tempData.email,
            "fullname": this.state.tempData.fullname,
            "company": this.state.company,
            "start_date": this.state.tempData.start_date,
            "end_date": this.state.tempData.end_date
        }

        api.create().updateUser(payload).then((response) => {        
            if (response.data.status == 'success') {
                this.props.onClickClose()
                this.props.refresh()
            } else {
                alert(response.data.message)
            }
        })
    }

    getRole() {
        api.create().getRole().then((response) => {
            if(response.data.status == 'success') {
                let data = response.data.data
                let roleData = data.map((item) => {
                    return {
                        role_id: item.role_id,
                        role_name: item.role_name
                    }
                })
                let defaultProps = {
                    options: roleData,
                    getOptionLabel: (option) => titleCase(option.role_name),
                  };

                let index = roleData.findIndex((val) => val.role_id == this.state.tempData.role_id)
                this.setState({listRole: defaultProps, role: index == -1? roleData[0] : roleData[index]})
            } else {
                alert(response.data.message)
            }
        })
    }

    getPerusahaan() {
        api.create().getPerusahaanHierarki().then((response) => {
            if(response.data.status == 'success') {
                this.setState({listCompany: response.data.data})
                console.log(response.data.data)
            }
        })
    }

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

    handleItemClick(item) {
        let indexID = this.state.company.findIndex((val) => val == item.company_id)
        let company = this.state.company
        if (indexID == -1) {
            company.push(item.company_id)
        } else {
            company.splice(indexID, 1)
        }
        this.setState({ company })
    }

    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' }}>Ubah 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="">
                                <TextField
                                    style={{ width: '100%' }}
                                    id="id"
                                    label="ID"
                                    disabled
                                    // id="outlined-read-only-input"
                                    variant="filled"
                                    value={this.state.tempData == null? '' : this.state.tempData.user_id}
                                    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="">
                                <TextField
                                style={{ width: '100%' , marginTop: 7}}
                                id="fullname"
                                name="fullname"
                                label="Nama Lengkap"
                                value={this.state.tempData == null? '' : this.state.tempData.fullname}
                                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">
                                <TextField
                                style={{ width: '100%' , marginTop: 7}}
                                id="email"
                                name="email"
                                label="Email"
                                value={this.state.tempData == null? '' : this.state.tempData.email}
                                onChange={(e) => this.handleChange(e, '')}
                                // defaultValue="Default Value"
                                // helperText="Some important text"
                                />
                            </div>
                        </div>

                        <div className="column-2">
                            <div className="margin-bottom-20px">
                                <Autocomplete
                                    {...this.state.listRole}
                                    id="role"
                                    onChange={(event, newInputValue) => this.setState({role: newInputValue})}
                                    debug
                                    renderInput={(params) => <TextField {...params} label="Role" margin="normal" style={{marginTop: 7}}/>}
                                    value={this.state.role}
                                />
                            </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.tempData == null ? null : this.state.tempData.start_date}
                                    error={this.state.errorStartDate}
                                    helperText={this.state.msgErrorSD}
                                    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.tempData == null ? null : this.state.tempData.end_date}
                                    error={this.state.errorEndDate}
                                    helperText={this.state.msgErrorED}
                                    minDate={this.state.tempData == null ? null : this.state.tempData.start_date}
                                    onChange={(e) => this.handleChange(e, 'end_date')}
                                    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={this.state.tempData == null? '' : this.state.tempData.status}
                                >
                                    {/* {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%' }}
                                    id="is_expired"
                                    name="is_expired"
                                    label="Expired"
                                    disabled
                                    // id="outlined-read-only-input"
                                    variant="filled"
                                    value={this.state.tempData == null? '' : this.state.tempData.is_expired}
                                >
                                    {/* {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  : ${this.state.tempData == null? '' : this.state.tempData.created}`}</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>Otorisasi Perusahaan</h5>
                        <div style={{paddingLeft: 10, overflow:'scroll', height: '25vh'}}>
                            {this.state.listCompany.map((item,index) => {
                                return(
                                    <div>
                                        <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start' }}>
                                            {item.childCompany.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 }}>{titleCase(item.company_name)}</Typography>
                                        </div>
                                        {item.childCompany.length > 0 && item.childCompany.map((items,indexs) => {
                                            return (
                                                <Collapse in={index == this.state.selectedIndex} timeout="auto" unmountOnExit>
                                                    <div style={{ paddingLeft: 60, 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>} */}
                                                        {/* <RemoveIcon color={'action'} fontSize={'small'} /> */}
                                                        <span>
                                                            <CustomCheckbox
                                                                checked={this.handleItemChecked(items)}
                                                                onChange={() => this.handleItemClick(items)}
                                                            />
                                                        </span>
                                                        <Typography style={{ fontSize: 12 }}>{titleCase(items.company_name)}</Typography>
                                                    </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' }}>
                            <button onClick={() => this.props.onClickClose()}>
                                <div 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>
                            </button>
                        </div>
                        <div className="column-2" style={{display: 'flex', justifyContent: 'flex-end', alignItems: 'center'}}>
                            <button onClick={() => this.validasi()}>
                                <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                    <span style={{ color: '#fff', fontSize: 11 }}>Simpan</span>
                                </div>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
