import React, { useState, useEffect } from 'react'
import { ValidatorForm, TextValidator } from 'react-material-ui-form-validator'
import { Button, Grid, FormControlLabel, Checkbox } from '@material-ui/core'

import { createPackage } from 'app/apis/Functions/landingpage'
import { showLoading, hideLoading } from 'app/redux/actions/loadingAction'
import { toast } from 'react-toastify'
import { Breadcrumb, SimpleCard } from 'app/components'
import { Link, useHistory, useLocation } from 'react-router-dom'
import { connect } from 'react-redux'
import { useTranslation } from 'react-i18next'
import {
    trimObject,
    toPriceVndInput,
    isNumeric,
    toPriceVnd,
} from 'app/config/Function'

import { dropdownFuncitonPackge } from 'app/apis/Functions/dropdown'

const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const [listFunc, setListFunc] = useState([])
    const [listChecked, setListChecked] = useState([])
    const { t } = useTranslation()
    const history = useHistory()

    useEffect(() => {
        getDataDropdown()
    }, [])
    const getDataDropdown = async () => {
        const res = await dropdownFuncitonPackge({})
        if (res.data.code == 200 && res.data.data) {
            setListFunc(res.data.data)
        }
    }

    const handleSubmit = async (event) => {
        const newValue = trimObject(state)

        if (
            isNumeric(newValue.price) ||
            newValue.price == '' ||
            !newValue.price
        ) {
            props.showLoading()
            const res = await createPackage({
                ...newValue,
                status: 1,
                outstand: 1,
                func_id_add: listChecked,
                price: newValue.price != '' ? newValue.price : null,
            })
            props.hideLoading()
            if (res.data.code == 200) {
                history.push('/package')
                if (res.data.code == 200) {
                    toast.success('Thêm mới gói thành công!', {
                        theme: 'colored',
                    })
                }
            } else {
                toast.error(t(res.data.error), {
                    theme: 'colored',
                })
            }
        } else {
            toast.warn('Đơn giá không đúng định dạng', {
                theme: 'colored',
            })
        }
    }

    const handleChange = (event) => {
        event.persist()
        console.log('event.target.name', event.target.name)
        if (event.target.name === 'price') {
            if (event.target.value !== null)
                setState({
                    ...state,
                    [event.target.name]: event.target.value.split('.').join(''),
                })
        } else
            setState({
                ...state,
                [event.target.name]: event.target.value,
            })
    }

    const handleDateChange = (date) => {
        setState({ ...state, date })
    }
    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 { pack_name, price } = state

    console.log('listChecked', listChecked)

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Danh sách gói',
                                path: '/package',
                            },
                            { 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
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tên gói*"
                                    onChange={handleChange}
                                    type="text"
                                    name="pack_name"
                                    value={pack_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
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Đơn giá"
                                    onChange={handleChange}
                                    type="text"
                                    name="price"
                                    value={toPriceVndInput(price) || ''}
                                />
                            </Grid>
                            <Grid row container item xs={12} sm={12}>
                                {listFunc.map((e) => (
                                    <Grid item xs={4}>
                                        <FormControlLabel
                                            label={e.func_name}
                                            control={
                                                <Checkbox
                                                    size="small"
                                                    color="primary"
                                                    onChange={onPicker}
                                                    name={e.id}
                                                    checked={listChecked.includes(
                                                        e.id
                                                    )}
                                                />
                                            }
                                        />
                                    </Grid>
                                ))}
                            </Grid>
                        </Grid>
                        <Grid container justify={'flex-end'}>
                            <Button
                                style={{
                                    marginRight: 20,
                                }}
                                color="inherit"
                                variant="contained"
                                onClick={() => {
                                    history.goBack()
                                }}
                            >
                                <span className="capitalize">Quay lại</span>
                            </Button>

                            <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 })(
    SimpleForm
)
