import React, { Component } from 'react';
import { Typography, AppBar, Tabs, Tab, TextField, Collapse, withStyles, Checkbox } from '@material-ui/core';
import HomePage from './HomePage';
import Images from '../assets/Images';
import api from '../api';
import Constant from '../library/Constant';
import RemoveIcon from '@material-ui/icons/Remove';
import AddIcon from '@material-ui/icons/Add';
import { titleCase } from '../library/Utils';

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

export default class Profile extends Component {
    constructor(props) {
        super(props)
        this.state = {
            tab: 0,
            oldPassword: '',
            password: '',
            confirmPassword: '',
            errorOldPassword: false,
            errorPassword: false,
            errorConfirmPassword: false,
            msgOldPassword: 'Terdiri 8 karakter dengan kombinasi angka.',
            msgPassword: 'Terdiri 8 karakter dengan kombinasi angka.',
            msgConfirmPassword: 'Terdiri 8 karakter dengan kombinasi angka.',
            company: [],
            listCompany: [],
            selectedIndex: 0
        }
    }

    componentDidMount() {
        this.getPerusahaan()
        this.getUser()
    }

    selectTab = (event, newEvent) => {
        this.setState({ tab: newEvent })
    }

    handleChange(e) {
        let data = this.state
        this.setState({ ...data, [e.target.name]: e.target.value })
        console.log(e.target.name);
        if (e.target.name == "password") {
            this.setState({ errorPassword: false, msgPassword: 'Terdiri 8 karakter dengan kombinasi angka.' })
        } else if (e.target.name == "confirmPassword") {
            this.setState({ errorConfirmPassword: false, msgConfirmPassword: 'Terdiri 8 karakter dengan kombinasi angka.' })
        } else if (e.target.name == "oldPassword") {
            this.setState({ errorOldPassword: false, msgOldPassword: 'Terdiri 8 karakter dengan kombinasi angka.' })
        }
    }

    validasi() {
        if (this.state.oldPassword == "") {
            this.setState({ errorOldPassword: true, msgOldPassword: 'Kata sandi lama harus diisi!' })
        } else if (this.state.oldPassword.length < 8) {
            this.setState({ errorOldPassword: true, msgOldPassword: 'Kata sandi lama minimal 8 karakter!' })
        } else if (this.isEmail(this.state.oldPassword)) {
            this.setState({ errorOldPassword: true, msgOldPassword: 'Format kata sandi lama tidak boleh menggunakan email!' })
        } else if (!this.isRegex(this.state.oldPassword)) {
            this.setState({ errorOldPassword: true, msgOldPassword: 'Kata sandi lama harus berupa kombinasi karakter, huruf dan angka!' })
        } else if (this.state.password.trim() == "") {
            this.setState({ errorPassword: true, msgPassword: 'Kata sandi baru harus diisi!' })
        } else if (this.state.password.length < 8) {
            this.setState({ errorPassword: true, msgPassword: 'Kata sandi baru minimal 8 karakter!' })
        } else if (this.isEmail(this.state.password)) {
            this.setState({ errorPassword: true, msgPassword: 'Format kata sandi baru tidak boleh menggunakan email!' })
        } else if (!this.isRegex(this.state.password)) {
            this.setState({ errorPassword: true, msgPassword: 'Kata sandi baru harus berupa kombinasi karakter, huruf dan angka!' })
        } else if (this.state.confirmPassword.trim() == "") {
            this.setState({ errorConfirmPassword: true, msgConfirmPassword: 'Konfirmasi kata sandi harus diisi!' })
        } else if (this.state.confirmPassword.length < 8) {
            this.setState({ errorConfirmPassword: true, msgConfirmPassword: 'Konfirmasi kata sandi minimal 8 karakter!' })
        } else if (this.isEmail(this.state.confirmPassword)) {
            this.setState({ errorConfirmPassword: true, msgConfirmPassword: 'Format konfirmasi kata sandi tidak boleh menggunakan email!' })
        } else if (!this.isRegex(this.state.confirmPassword)) {
            this.setState({ errorConfirmPassword: true, msgConfirmPassword: 'Konfirmasi kata sandi harus berupa kombinasi karakter, huruf dan angka!' })
        } else if (this.state.password !== this.state.confirmPassword) {
            this.setState({ errorConfirmPassword: true, msgConfirmPassword: 'Konfirmasi kata sandi harus sama dengan kata sandi baru!' })
        } else {
            this.confirmPassword()
        }
    }

    confirmPassword() {
        let body = {
            "old_password": this.state.oldPassword,
            "new_password": this.state.password,
            "confirm_password": this.state.confirmPassword
        }
        api.create().changePassword(body).then(response => {
            console.log(response);
            if (response.data.status === "success") {
                this.setState({ oldPassword: "", password: "", confirmPassword: "" })
                alert(response.data.message)
            } else {
                alert(response.data.message)
            }
        })
    }

    isRegex(value) {
        // const re = /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/;
        const re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{1,}$/;
        return re.test(String(value));
    }

    isEmail(email) {
        const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    }

    getUser() {
        let userId = localStorage.getItem(Constant.USER)
        api.create().getDetailUser(userId).then((response) => {
            if (response.data.status == 'success') {
                this.setState({ company: response.data.data.company })
                console.log(response)
            }

        })
    }

    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
    }

    render() {
        return (
            <div style={{ height: this.props.height, backgroundColor: '#f8f8f8', marginBottom: 100, minHeight: 1000 }}>
                <div className={"main-color"} style={{ height: 203, flex: 1, display: 'flex', alignItems: 'flex-end', padding: 20 }}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <div style={{ height: 72, width: 72, backgroundColor: 'white', borderRadius: 40, marginRight: 20 }} />
                        <Typography style={{ fontSize: '24px', color: 'white', fontWeight: 'bold' }}>John Doe</Typography>
                    </div>
                </div>
                <div>
                    <AppBar position="static">
                        <Tabs indicatorColor="primary" value={this.state.tab} onChange={this.selectTab} aria-label="simple tabs example" style={{ backgroundColor: '#f8f8f8', borderColor: 'transparent' }}>
                            <Tab label="KATA SANDI" style={{ color: '#4b4b4b', fontSize: 11 }} />
                            <Tab label="OTORISASI PERUSAHAAN" style={{ color: '#4b4b4b', fontSize: 11 }} />
                        </Tabs>
                    </AppBar>
                    {this.state.tab == 0 ?
                        <div style={{ padding: 20, marginTop: 10, marginBottom: 100 }}>
                            <div style={{ width: 432, borderRadius: 6, boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.25)' }}>
                                <div style={{ width: '100%', height: 64, backgroundColor: '#354960', display: 'flex', paddingLeft: 20, borderTopLeftRadius: 6, borderTopRightRadius: 6, alignItems: 'center' }}>
                                    <Typography style={{ fontSize: '13px', color: 'white', fontWeight: 'bold' }}>Kata Sandi</Typography>
                                </div>
                                <div style={{ padding: 20, justifyContent: 'space-between' }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        inputProps={{ style: { fontSize: 11 } }}
                                        id="filled-required"
                                        name={"oldPassword"}
                                        label="Kata Sandi Saat Ini"
                                        value={this.state.oldPassword}
                                        variant="outlined"
                                        onChange={(password) => {
                                            this.handleChange(password)
                                        }}
                                        error={this.state.errorOldPassword}
                                        helperText={<Typography style={{ fontSize: 9, marginTop: 4, fontFamily: 'Nunito Sans, sans-serif' }}>{this.state.msgOldPassword}</Typography>}
                                    />
                                    <TextField
                                        style={{ width: '100%', marginTop: 20 }}
                                        inputProps={{ style: { fontSize: 11 } }}
                                        id="filled-required"
                                        label="Kata Sandi Baru"
                                        name={"password"}
                                        value={this.state.password}
                                        onChange={(password) => {
                                            this.handleChange(password)
                                        }}
                                        error={this.state.errorPassword}
                                        helperText={<Typography style={{ fontSize: 9, marginTop: 4, fontFamily: 'Nunito Sans, sans-serif' }}>{this.state.msgPassword}</Typography>}
                                        variant="outlined"
                                    />
                                    <TextField
                                        style={{ width: '100%', marginTop: 20 }}
                                        inputProps={{ style: { fontSize: 11 } }}
                                        id="filled-required"
                                        label="Konfirmasi Kata Sandi Baru"
                                        name={"confirmPassword"}
                                        value={this.state.confirmPassword}
                                        onChange={(confirmPassword) => {
                                            this.handleChange(confirmPassword)
                                        }}
                                        variant="outlined"
                                        error={this.state.errorConfirmPassword}
                                        helperText={<Typography style={{ fontSize: 9, marginTop: 4, fontFamily: 'Nunito Sans, sans-serif' }}>{this.state.msgConfirmPassword}</Typography>}
                                    />
                                </div>
                                <div style={{ width: '100%', backgroundColor: '#f5f5f5', height: 43, display: 'flex', justifyContent: 'flex-end', padding: 10, borderColor: 'rgba(0, 0, 0, 0.25)', borderWidth: .2, borderStyle: 'dotted' }}>
                                    <button
                                        type="button"
                                        onClick={() => this.validasi()}
                                        style={{}}
                                    >
                                        <div style={{ backgroundColor: '#354960', textAlign: 'center', height: 25, width: 64, borderRadius: 3 }}>
                                            <span style={{ color: 'white', fontSize: 11 }}>Simpan</span>
                                        </div>
                                    </button>
                                </div>
                            </div>
                        </div> :
                        <div style={{ padding: 20, marginTop: 10, marginBottom: 100 }}>
                            <div style={{ width: 432, borderRadius: 6, boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.25)' }}>
                                <div style={{ width: '100%', height: 64, backgroundColor: '#354960', display: 'flex', paddingLeft: 20, borderTopLeftRadius: 6, borderTopRightRadius: 6, alignItems: 'center' }}>
                                    <Typography style={{ fontSize: '13px', color: 'white', fontWeight: 'bold' }}>Otorisasi Perusahaan</Typography>
                                </div>
                                <div style={{ padding: 20, overflow: 'scroll', height: '40vh' }}>
                                    {/* <div style={{ display: 'flex' }}>
                                        <img src={Images.check} style={{ marginRight: 10 }} />
                                        <Typography style={{ fontSize: 14, opacity: .5, color: '#4b4b4b' }}>Agro PersadaTriputra </Typography>
                                    </div>
                                    <div style={{ display: 'flex', marginTop: 20 }}>
                                        <img src={Images.check} style={{ marginRight: 10 }} />
                                        <Typography style={{ fontSize: 14, opacity: .5, color: '#4b4b4b' }}>Dharma Group</Typography>
                                    </div>
                                    <div style={{ display: 'flex', marginTop: 20, paddingLeft: 20 }}>
                                        <img src={Images.check} style={{ marginRight: 10 }} />
                                        <Typography style={{ fontSize: 14, opacity: .5, color: '#4b4b4b' }}>Dharma Polimetal</Typography>
                                    </div>
                                    <div style={{ display: 'flex', marginTop: 20, paddingLeft: 20 }}>
                                        <img src={Images.check} style={{ marginRight: 10 }} />
                                        <Typography style={{ fontSize: 14, opacity: .5, color: '#4b4b4b' }}>Dharma Poliplast</Typography>
                                    </div> */}
                                    {this.state.listCompany.map((item, index) => {
                                        return (
                                            <div>
                                                <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start' }}>
                                                    <span>
                                                        <CustomCheckbox
                                                            disabled={true}
                                                            disabled={true}
                                                            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: 30, 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
                                                                        disabled={true}
                                                                        checked={this.handleItemChecked(items)}
                                                                    // onChange={() => this.handleItemClick(items)}
                                                                    />
                                                                </span>
                                                                <Typography style={{ fontSize: 12 }}>{titleCase(items.company_name)}</Typography>
                                                            </div>
                                                        </Collapse>

                                                    )
                                                })}
                                            </div>
                                        )
                                    })}
                                </div>
                            </div>
                        </div>
                    }
                </div>
            </div>
        );
    }
}
