import React, { Component } from 'react';
import { TextField, Typography } from '@material-ui/core';
import { DateTimePicker, KeyboardDatePicker, DatePicker } from "@material-ui/pickers";
import Autocomplete from '@material-ui/lab/Autocomplete';
import * as R from 'ramda'
import format from "date-fns/format";
import api from "../../api";
import Images from '../../assets/Images';
import Constant from '../../library/Constant';
import { fetchMasterReportType } from '../../utils/services';
import AutocompleteField from '../../library/AutocompleteField';
import { convertSelect } from '../../library/Utils';

export default class EditApprovalMatrix extends Component {
    constructor(props) {
        super(props)
        this.state = {
            id: '',
            order: '',
            status: "",
            startDate: null,
            endDate: null,
            date: new Date(),
            approvedBy: null,
            getApprovedBy: null,
            types: null,
            getTypes: null,
            operators: null,
            getOperators: null,
            errorType: false,
            msgErrType: '',
            errorApproved: false,
            msgErrApproved: '',
            errorOperator: false,
            msgErrOperator: '',
            errorOrder: false,
            msgErrOrder: '',
            errorStartDate: false,
            errorEndDate: false,
            msgErrorStartDate: "",
            msgErrorEndDate: "",

            master_report_type_id: null,
            listMasterReportType: [],
            errorMasterReportTypeId: false,
            msgErrMasterReportTypeId: '',
        }
    }

    componentDidMount() {
        if (this.props.type === 'edit') {
            this.getDetailAM()
            // let getApprovedBy = {
            //     user_id: data.user_id,
            //     fullname: data.fullname
            // })
        }
    }

    getMasterBudgetType = async () => {
        const { data } = await fetchMasterReportType();

        if (data) {
            const list = data.map((item) => ({
                id: item.master_report_type_id,
                name: item.master_report_type_name
            }));

            this.setState({ listMasterReportType: list });
        } else {
            this.setState({ listMasterReportType: [] });
        }
    }

    getDetailAM() {
        api.create().getDetailAM(this.props.data[1]).then(response => {
            console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === "success") {
                        let data = response.data.data
                        this.setState({
                            id: data.approval_matrix_id,
                            startDate: data.start_date,
                            endDate: data.end_date,
                            order: data.orders,
                            getUserId: data.user_id,
                            getTypeId: data.approval_type_id,
                            getOperatorId: data.operator_type_id,
                            status: data.status,
                            created: data.created,
                            updated: data.updated === null ? "" : data.updated,
                            master_report_type_id: convertSelect(data?.master_report_type_id, data?.master_report_type_name)
                        }, () => this.getUserData(), this.getTypeData(), this.getOperatorData(), this.getMasterBudgetType())
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getUserData() {
        api.create().getApprovedByAM().then((response) => {
            console.log(response);
            console.log(this.state.getUserId);
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let data = response.data.data
                        let userData = data.map((item) => {
                            return {
                                user_id: item.user_id,
                                fullname: item.fullname == null ? "(NO_NAME)" : item.fullname
                            }
                        })
                        let index = userData.findIndex((val) => val.user_id == this.state.getUserId)
                        let defaultProps = {
                            options: userData,
                            getOptionLabel: (option) => option.fullname,
                        };
                        // this.setState({ approvedBy: defaultProps, userData: response.data.data, getApprovedBy: index == -1 ? userData[0]: userData[index] })
                        this.setState({ approvedBy: defaultProps, userData: response.data.data, getApprovedBy: index == -1 ? this.setState({ errorApproved: true, msgErrApproved: 'Approver Name has been Inactive.' }) : userData[index] })

                    } else {
                        // alert('Pemberi Persetujuan: ' +response.data.message)
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            })
                        } else {
                            this.setState({ alert: true, messageAlert: 'Pemberi Persetujuan: ' + response.data.message, tipeAlert: 'error' })
                        }
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getOperatorData() {
        api.create().getOperatorAM().then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let data = response.data.data
                        let operatorData = data.map((item) => {
                            return {
                                operator_type_id: item.operator_type_id,
                                operator_type_name: item.operator_type_name
                            }
                        })
                        let index = operatorData.findIndex((val) => val.operator_type_id == this.state.getOperatorId)
                        let operatorProps = {
                            options: operatorData,
                            getOptionLabel: (option) => option.operator_type_name,
                        };
                        this.setState({ operators: operatorProps, operatorData: response.data.data, getOperators: index == -1 ? operatorData[0] : operatorData[index] })
                    } else {
                        // alert('Operator: ' +response.data.message)
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            })
                        } else {
                            this.setState({ alert: true, messageAlert: 'Operator: ' + response.data.message, tipeAlert: 'error' })
                        }
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getTypeData() {
        api.create().getTypeAM().then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let data = response.data.data
                        let typeData = data.map((item) => {
                            return {
                                approval_type_id: item.approval_type_id,
                                approval_type_name: item.approval_type_name
                            }
                        })
                        let index = typeData.findIndex((val) => val.approval_type_id == this.state.getTypeId)
                        let typeProps = {
                            options: typeData,
                            getOptionLabel: (option) => option.approval_type_name,
                        };
                        this.setState({ types: typeProps, typeData: response.data.data, getTypes: index == -1 ? typeData[0] : typeData[index] })
                    } else {
                        // alert('Approval Type: ' +response.data.message)
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            })
                        } else {
                            this.setState({ alert: true, messageAlert: 'Approval Type: ' + response.data.message, tipeAlert: 'error' })
                        }
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }


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

    }

    handleChangeDropdown = (newValue, name) => {
        this.setState(prevState => ({
            ...prevState,
            [name]: newValue,
        }), () => {
            this.clearError();
        })
    }

    clearError() {
        this.setState({
            errorType: false,
            msgErrType: '',
            errorApproved: false,
            msgErrApproved: '',
            errorOperator: false,
            msgErrOperator: '',
            errorOrder: false,
            msgErrOrder: "",
            errorStartDate: false,
            errorEndDate: false,
            msgErrorStartDate: "",
            msgErrorEndDate: "",
            errorMasterReportTypeId: false,
            msgErrMasterReportTypeId: '',
        })
    }

    validasi() {
        if (R.isNil(this.state.getTypes)) {
            this.setState({ errorType: true, msgErrType: 'Approval Type Cannot be Empty' })
        }
        else if (R.isEmpty(this.state.order)) {
            this.setState({ errorOrder: true, msgErrOrder: 'Order Cannot be Empty' })
        }
        else if (R.isNil(this.state.getApprovedBy)) {
            this.setState({ errorApproved: true, msgErrApproved: 'Approver Name Cannot be Empty' })
        }
        else if (R.isNil(this.state.getOperators)) {
            this.setState({ errorOperator: true, msgErrOperator: 'Operator Cannot be Empty' })
        }
        else if (R.isNil(this.state.master_report_type_id)) {
            this.setState({ errorMasterReportTypeId: true, msgErrMasterReportTypeId: 'Master Report Type Cannot be Empty. Please Choose - Option' })
        }
        else if (R.isEmpty(this.state.startDate)) {
            this.setState({ errorStartDate: true, msgErrorStartDate: 'Valid From Cannot be Empty' })
        } else if (R.isEmpty(this.state.endDate)) {
            this.setState({ errorEndDate: true, msgErrorEndDate: 'Valid To Cannot be Empty' })
        } else {
            if (this.props.type == 'edit') {
                let payload = {
                    "approval_matrix_id": this.state.id,
                    "approval_type_id": this.state.getTypes.approval_type_id,
                    "orders": this.state.order,
                    "user_id": this.state.getApprovedBy.user_id,
                    "operator_type_id": this.state.getOperators.operator_type_id,
                    "master_report_type_id": this.state.master_report_type_id?.id ?? null,
                    "start_date": this.state.startDate,
                    "end_date": this.state.endDate
                }
                this.props.updateAM(payload)
            }
        }
    }

    render() {
        return (
            <div className="test app-popup-show" style={{ paddingTop: 100 }}>
                <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                    <div className="popup-panel grid grid-2x main-color" style={{ 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' }}>Edit 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()}
                            >
                                <img src={Images.close} />
                            </button>
                        </div>
                    </div>

                    <div className="border-bottom" style={{ padding: 20 }}>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div style={{ backgroundColor: '#e8e8e8', padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        id="id"
                                        label="ID"
                                        value={this.state.id}
                                        disabled
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.types}
                                        option
                                        debug
                                        id="tipe"
                                        onChange={(event, newInputValue) => this.setState({ getTypes: newInputValue }, () => this.clearError())}
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                label="Approval Type"
                                                onChange={(e) => this.handleChange(e, '')}
                                                error={this.state.errorType}
                                                helperText={this.state.msgErrType}
                                                InputLabelProps={{
                                                    style: {
                                                        fontSize: 11,
                                                        color: '#7e8085'
                                                    }
                                                }}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                            />}
                                        value={this.state.getTypes}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        id="order"
                                        label="Order"
                                        value={this.state.order === null ? '' : this.state.order}
                                        error={this.state.errorOrder}
                                        helperText={this.state.msgErrOrder}
                                        // onChange={(e) => this.setState({ order: e.target.value }, () => this.clearError())}
                                        onChange={(e) => {
                                            let coba = String(e.target.value).replace(/[^\d]/g, '');
                                            this.setState({
                                                order: coba
                                            },
                                                () => this.clearError())
                                        }
                                            // this.handleChange(coba, 'value')}
                                        }
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    // name="order"
                                    >
                                    </TextField>
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.approvedBy}
                                        option
                                        debug
                                        id="approvedby"
                                        onChange={(event, newInputValue) => this.setState({ getApprovedBy: newInputValue }, () => this.clearError())}
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                label="Approver Name"
                                                onChange={(e) => this.handleChange(e, '')}
                                                error={this.state.errorApproved}
                                                helperText={this.state.msgErrApproved}
                                                InputLabelProps={{
                                                    style: {
                                                        fontSize: 11,
                                                        color: '#7e8085'
                                                    }
                                                }}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                            />}
                                        value={this.state.getApprovedBy}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.operators}
                                        option
                                        debug
                                        id="operator"
                                        onChange={(event, newInputValue) => this.setState({ getOperators: newInputValue }, () => this.clearError())}
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                label="Operator"
                                                onChange={(e) => this.handleChange(e, '')}
                                                error={this.state.errorOperator}
                                                helperText={this.state.msgErrOperator}
                                                InputLabelProps={{
                                                    style: {
                                                        fontSize: 11,
                                                        color: '#7e8085'
                                                    }
                                                }}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                            />}
                                        value={this.state.getOperators}
                                    />
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <AutocompleteField
                                        options={this.state.listMasterReportType}
                                        value={this.state.master_report_type_id}
                                        onChange={(event, newValue) => this.handleChangeDropdown(newValue, 'master_report_type_id')}
                                        label="Master Report Type"
                                        minSizeBox={true}
                                        error={this.state.errorMasterReportTypeId}
                                        helperText={this.state.msgErrMasterReportTypeId}
                                        disableClearable={false}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <DatePicker
                                        margin="normal"
                                        id="startDate"
                                        label="Valid From"
                                        format="dd MMMM yyyy"
                                        value={this.state.startDate}
                                        onChange={(e) => this.handleChange(e, 'start_date')}
                                        KeyboardButtonProps={{
                                            'aria-label': 'change date',
                                        }}
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                        error={this.state.errorStartDate}
                                        helperText={this.state.msgErrorStartDate}
                                        style={{ padding: 0, margin: 0, width: '100%' }}
                                    />
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <DatePicker
                                        margin="normal"
                                        id="endDate"
                                        label="Valid To"
                                        format="dd MMMM yyyy"
                                        error={this.state.errorEndDate}
                                        helperText={this.state.msgErrorEndDate}
                                        minDate={this.state.startDate}
                                        value={this.state.endDate}
                                        onChange={(e) => this.handleChange(e, 'end_date')}
                                        KeyboardButtonProps={{
                                            'aria-label': 'change date',
                                        }}
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                        style={{ padding: 0, margin: 0, width: '100%' }}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ backgroundColor: '#e8e8e8', padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        value={this.state.status}
                                        id="status"
                                        label="Status"
                                        disabled
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    >
                                    </TextField>
                                </div>
                            </div>
                            <div className="column-2">
                                {/* <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        id="max-value"
                                        label="Max Value"
                                        value="10"
                                        onChange={(e) => this.handleChange(e, '')}
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    >
                                    </TextField>
                                </div> */}
                            </div>
                        </div>
                        <div className="margin-top-10px" style={{ paddingTop: 10, paddingBottom: 10, paddingLeft: 10, paddingRight: 20 }}>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '12%' }}>Created By</Typography>
                                <Typography style={{ fontSize: 11 }}>: {this.state.created}</Typography>
                            </div>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '12%' }}>Updated By</Typography>
                                <Typography style={{ fontSize: 11 }}>: {this.state.updated == - null ? "" : this.state.updated}</Typography>
                            </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', cursor: "pointer" }}>
                                <span style={{ color: '#354960', fontSize: 11 }} >Cancel</span>
                            </div>
                        </div>
                        <div className="column-2" style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                            <div onClick={() => this.validasi()} style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor: "pointer" }}>
                                <span style={{ color: '#fff', fontSize: 11 }}>Save</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
