import {
    Button,
    Checkbox,
    FormControlLabel,
    Grid,
    Typography,
} from '@material-ui/core'
import { Breadcrumb, SimpleCard } from 'app/components'
import { trimObject } from 'app/config/Function'
import { hideLoading, showLoading } from 'app/redux/actions/loadingAction'
import React, { useEffect, useState } from 'react'
import { TextValidator, ValidatorForm } from 'react-material-ui-form-validator'
import { connect } from 'react-redux'
import { Link, useHistory, useLocation } from 'react-router-dom'

import { dropdownPermission } from 'app/apis/Functions/dropdown'
import { detailGroup, updateGroup } from 'app/apis/Functions/GroupRole'
import useAuth from 'app/hooks/useAuth'
import { useTranslation } from 'react-i18next'
import { toast } from 'react-toastify'

function CreateDeparment(props) {
    const { user } = useAuth()
    const location = useLocation()
    const history = useHistory()
    const [state, setState] = useState({})
    const [listMethod, setListMethod] = useState([])
    const [listChecked, setListChecked] = useState([])
    const [defaultGroup, setDefaultGroup] = useState([])

    const { t } = useTranslation()

    useEffect(() => {
        getData()
        getDataDropDown()
    }, [])

    useEffect(() => {
        getListDefault()
    }, [defaultGroup])

    const getListDefault = () => {
        const newList = defaultGroup.map((e) => {
            return e.action_id
        })
        setListChecked(newList)
    }

    const getDataDropDown = async () => {
        const res = await dropdownPermission()
        if (res.data.code == 200 && res.data.data && res.data.data.data) {
            setListMethod(res.data.data.data)
        }
    }

    const getData = async () => {
        props.showLoading()
        const res = await detailGroup(location.state, {})
        if (res.data.code == 200) {
            setState(res.data.data)
            setDefaultGroup(res.data.data.userGroupPermissions)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
        props.hideLoading()
    }
    const handleSubmit = async (value) => {
        if (state) {
            const newValue = trimObject(state)
            const newList = listChecked.map((e) => {
                return { action_id: e }
            })
            props.showLoading()
            const res = await updateGroup({
                ...newValue,
                userGroupPermissions: newList,
            })

            props.hideLoading()

            if (res.data.code == 200) {
                history.push('/group-role')
                toast.success('Cập nhật thành công!', {
                    theme: 'colored',
                })
            } else {
                toast.error(t(res.data.error), {
                    theme: 'colored',
                })
            }
        }
    }

    const handleChange = (event) => {
        event.persist()
        setState({
            ...state,
            [event.target.name]: event.target.value,
        })
    }

    const onPicker = (value) => {
        if (value.target.checked) {
            const newList = listChecked.concat(value.target.name)
            setListChecked(newList)
        } else {
            const newList = listChecked.filter((e) => {
                return e != value.target.name
            })
            setListChecked(newList)
        }
    }

    const { name, description } = state

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Quản lý nhóm',
                                path: '/group-role',
                            },
                            { name: 'Cập nhật' },
                        ]}
                    />
                </div>

                <SimpleCard>
                    <ValidatorForm onSubmit={handleSubmit} onError={() => null}>
                        <Grid container spacing={3}>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    className="mb-4 w-full"
                                    label="Tên nhóm*"
                                    onChange={handleChange}
                                    variant="outlined"
                                    type="text"
                                    name="name"
                                    value={name || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    className="mb-4 w-full"
                                    label="Mô tả *"
                                    onChange={handleChange}
                                    variant="outlined"
                                    type="text"
                                    name="description"
                                    value={description || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>
                            <Grid item xs={12} sm={12}>
                                <Typography variant={'h6'}>
                                    Phân quyền
                                </Typography>
                                {listMethod.length > 0 ? (
                                    <Grid lg={12} md={12} sm={12} xs={12} item>
                                        {listMethod.map((items) => {
                                            const { name, list_actions } = items
                                            return (
                                                <>
                                                    <Typography variant={'h6'}>
                                                        {name}
                                                    </Typography>
                                                    <Grid
                                                        row
                                                        container
                                                        item
                                                        xs={12}
                                                        sm={12}
                                                    >
                                                        {list_actions &&
                                                            list_actions.map(
                                                                (action) => (
                                                                    <Grid
                                                                        item
                                                                        xs={3}
                                                                    >
                                                                        <FormControlLabel
                                                                            label={
                                                                                action.name
                                                                            }
                                                                            control={
                                                                                <Checkbox
                                                                                    size="small"
                                                                                    color="primary"
                                                                                    name={
                                                                                        action.id
                                                                                    }
                                                                                    onChange={
                                                                                        onPicker
                                                                                    }
                                                                                    checked={listChecked.includes(
                                                                                        action.id
                                                                                    )}
                                                                                />
                                                                            }
                                                                        />
                                                                    </Grid>
                                                                )
                                                            )}
                                                    </Grid>
                                                </>
                                            )
                                        })}
                                    </Grid>
                                ) : null}
                            </Grid>
                        </Grid>
                        <Grid container justify={'flex-end'}>
                            <Link to="/group-role">
                                <Button
                                    style={{
                                        marginRight: 20,
                                        boxShadow: 'none',
                                    }}
                                    color="inherit"
                                    variant="contained"
                                    onClick={() => {}}
                                >
                                    <span className="capitalize">Quay lại</span>
                                </Button>
                            </Link>
                            <Button
                                color="primary"
                                variant="contained"
                                type="submit"
                            >
                                <span className="capitalize">Cập nhật</span>
                            </Button>
                        </Grid>
                    </ValidatorForm>
                </SimpleCard>
            </div>
        </div>
    )
}

const mapStateToProps = (state) => {
    return {}
}
export default connect(mapStateToProps, { showLoading, hideLoading })(
    CreateDeparment
)