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

import {
    detailPriceProduct,
    updatePriceProduct,
} 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 { trimObject, toPriceVndInput, isNumeric } from 'app/config/Function'
import { connect } from 'react-redux'
import localStorageService from 'app/services/localStorageService'
import { useTranslation } from 'react-i18next'
import {
    dropdownTypeEquipment,
    dropdownTypeCaculator,
    dropdownNcc,
} from 'app/apis/Functions/dropdown'

const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const history = useHistory()
    const location = useLocation()
    const { t } = useTranslation()
    const [listTypeEquipment, setListEquipment] = useState([])
    const [listTypeCaculator, setListCaculator] = useState([])
    const [listNcc, setListNcc] = useState([])

    useEffect(() => {
        getDataDropdown()
        getData()
    }, [])
    const getDataDropdown = async () => {
        const resTypeEquipment = await dropdownTypeEquipment({})
        if (resTypeEquipment.data.code == 200 && resTypeEquipment.data.data) {
            setListEquipment(resTypeEquipment.data.data)
        }
        const resTypeCaculator = await dropdownTypeCaculator({})
        if (resTypeCaculator.data.code == 200 && resTypeCaculator.data.data) {
            setListCaculator(resTypeCaculator.data.data)
        }

        const resNcc = await dropdownNcc({})
        if (resNcc.data.code == 200 && resNcc.data.data) {
            const newList = resNcc.data.data.map((e) => {
                return { ...e, name: e?.supp_name }
            })
            setListNcc(newList)
        }
    }

    const getData = async () => {
        props.showLoading()
        const res = await detailPriceProduct(location.state, {})
        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            setState(res.data.data)
        } else if (res.data.code == 401) {
            localStorageService.removeToken()
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const handleSubmit = async (event) => {
        const newValue = trimObject(state)
        props.showLoading()
        if (
            isNumeric(newValue.price) ||
            newValue.price == '' ||
            !newValue.price
        ) {
            const res = await updatePriceProduct({
                ...newValue,
                price: newValue.price != '' ? newValue.price : null,
            })
            props.hideLoading()
            if (res.data.code == 200) {
                history.push('/price-product')
                if (res.data.code == 200) {
                    toast.success('Cập nhật sản phẩm 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()

        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 {
        cons_name,
        unit,
        price,
        type_caculator,
        type,
        suppconstruction_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: '/price-product',
                            },
                            { 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
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tên sản phẩm *"
                                    onChange={handleChange}
                                    type="text"
                                    name="cons_name"
                                    value={cons_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 vị tính"
                                    onChange={handleChange}
                                    type="text"
                                    name="unit"
                                    value={unit || ''}
                                    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}
                                    name="price"
                                    type="text"
                                    value={toPriceVndInput(price) || ''}
                                />
                            </Grid>
                            {type_caculator && (
                                <Grid xs={6} sm={6} item>
                                    <SelectValidator
                                        variant={'outlined'}
                                        label={'Cách tính *'}
                                        className="mb-4 w-full"
                                        value={type_caculator || ''}
                                        displayEmpty
                                        name="type_caculator"
                                        onChange={handleChange}
                                        validators={['required']}
                                        errorMessages={[
                                            'Không được để trống trường này',
                                        ]}
                                    >
                                        {listTypeCaculator.map((e) => (
                                            <MenuItem value={e.code}>
                                                {e.name}
                                            </MenuItem>
                                        ))}
                                    </SelectValidator>
                                </Grid>
                            )}

                            {type && (
                                <Grid xs={6} sm={6} item>
                                    <SelectValidator
                                        variant={'outlined'}
                                        label={'Loại sản phẩm *'}
                                        className="mb-4 w-full"
                                        value={type || ''}
                                        displayEmpty
                                        name="type"
                                        onChange={handleChange}
                                        validators={['required']}
                                        errorMessages={[
                                            'Không được để trống trường này',
                                        ]}
                                    >
                                        {listTypeEquipment.map((e) => (
                                            <MenuItem value={e.code}>
                                                {e.name}
                                            </MenuItem>
                                        ))}
                                    </SelectValidator>
                                </Grid>
                            )}
                            {suppconstruction_id && (
                                <Grid xs={6} sm={6} item>
                                    <SelectValidator
                                        variant={'outlined'}
                                        label={'Nhà cung cấp *'}
                                        className="mb-4 w-full"
                                        value={suppconstruction_id || ''}
                                        displayEmpty
                                        name="suppconstruction_id"
                                        onChange={handleChange}
                                        validators={['required']}
                                        errorMessages={[
                                            'Không được để trống trường này',
                                        ]}
                                    >
                                        {listNcc.map((e) => (
                                            <MenuItem value={e.id}>
                                                {e.name}
                                            </MenuItem>
                                        ))}
                                    </SelectValidator>
                                </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">Cập nhật</span>
                            </Button>
                        </Grid>
                    </ValidatorForm>
                </SimpleCard>
            </div>
        </div>
    )
}

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