import {
    Button,
    Checkbox,
    FormControlLabel,
    Grid,
    Typography,
} from '@material-ui/core'
import { dropdownPermission } from 'app/apis/Functions/dropdown'
import { createGroup } from 'app/apis/Functions/GroupRole'
import { Breadcrumb, SimpleCard } from 'app/components'
import { trimObject } from 'app/config/Function'
import useAuth from 'app/hooks/useAuth'
import { hideLoading, showLoading } from 'app/redux/actions/loadingAction'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { TextValidator, ValidatorForm } from 'react-material-ui-form-validator'
import { connect } from 'react-redux'
import { Link, useHistory } from 'react-router-dom'
import { toast } from 'react-toastify'

function CreateDeparment(props) {
    const { user } = useAuth()

    const history = useHistory()
    const [state, setState] = useState({})
    const [listMethod, setListMethod] = useState([])
    const [listChecked, setListChecked] = useState([])

    const { t } = useTranslation()
    useEffect(() => {
        getData()
    }, [])

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

    const handleSubmit = async (value) => {
        if (state) {
            const newValue = trimObject(state)
            const newList = listChecked.map((e) => {
                return { action_id: e }
            })
            props.showLoading()
            const res = await createGroup({
                ...newValue,
                userGroupPermissions: newList,
                status: 1,
            })
            props.hideLoading()

            if (res.data.code == 200) {
                history.push('/group-role')
                toast.success('Thêm mới 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: 'Thêm mới' },
                        ]}
                    />
                </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">Thêm mới</span>
                            </Button>
                        </Grid>
                    </ValidatorForm>
                </SimpleCard>
            </div>
        </div>
    )
}

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