import React, { useState, useEffect } from 'react'
import {
    ValidatorForm,
    TextValidator,
    SelectValidator,
} from 'react-material-ui-form-validator'
import {
    Button,
    Icon,
    Grid,
    Radio,
    RadioGroup,
    FormControlLabel,
    Checkbox,
    TextField,
    Typography,
    MenuItem,
    Select,
    InputLabel,
} from '@material-ui/core'

import { Breadcrumb, SimpleCard } from 'app/components'
import { dropdownProductType } from 'app/apis/Functions/dropdown'
import { Link, useHistory, useLocation } from 'react-router-dom'
import { toast } from 'react-toastify'
import { trimObject, toPriceVndInput, isNumeric } from 'app/config/Function'
import { connect } from 'react-redux'
import { showLoading, hideLoading } from 'app/redux/actions/loadingAction'
import { createProduct } from 'app/apis/Functions/product'
import { useTranslation } from 'react-i18next'
const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const [listDrop, setListDrop] = useState([])
    const history = useHistory()
    const { t } = useTranslation()
    useEffect(() => {
        getData()
    }, [])
    const getData = async () => {
        props.showLoading()
        const res = await dropdownProductType({})
        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            const newList = res.data.data.map((e) => {
                return { name: e.type_name, value: e.id, ...e }
            })
            setListDrop(newList)
        } else if (res.data.code == 401) {
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

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

        if (isNumeric(newValue.price_default)) {
            props.showLoading()
            const res = await createProduct({
                ...newValue,
            })
            props.hideLoading()
            if (res.data.code == 200) {
                history.push('/product')
                if (res.data.code == 200) {
                    toast.success('Tạo sản phẩm thành công!', {
                        theme: 'colored',
                    })
                }
            } else {
                toast.error(t(res.data.error), {
                    theme: 'colored',
                })
            }
        } else {
            toast.error('Giá mặc định không đúng định dạng', {
                theme: 'colored',
            })
        }
    }

    const handleChange = (event) => {
        event.persist()

        if (event.target.name === 'price_default') {
            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 { name, code, price_default, type_id } = state

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Danh sách sản phẩm',
                                path: '/product',
                            },
                            { name: 'Thêm mới sản phẩm' },
                        ]}
                    />
                </div>
                <SimpleCard>
                    <ValidatorForm onSubmit={handleSubmit} onError={() => null}>
                        <Grid container spacing={3}>
                            <Grid xs={6} sm={6} item>
                                <SelectValidator
                                    variant={'outlined'}
                                    label={'Thuộc loại sản phẩm *'}
                                    className="mb-4 w-full"
                                    value={type_id || ''}
                                    displayEmpty
                                    name="type_id"
                                    onChange={handleChange}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                >
                                    {listDrop.map((e) => (
                                        <MenuItem value={e.id}>
                                            {e.name}
                                        </MenuItem>
                                    ))}
                                </SelectValidator>
                            </Grid>

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tên *"
                                    onChange={handleChange}
                                    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
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Mã code *"
                                    onChange={handleChange}
                                    type="text"
                                    name="code"
                                    value={code || ''}
                                    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="Giá mặc định *"
                                    onChange={handleChange}
                                    type="text"
                                    name="price_default"
                                    value={toPriceVndInput(price_default) || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>
                        </Grid>
                        <Grid container justify={'flex-end'}>
                            <Link to="/product">
                                <Button
                                    style={{
                                        marginRight: 20,
                                    }}
                                    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 })(
    SimpleForm
)
