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

import { createPageStatic } from 'app/apis/Functions/pageStatic'
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, convertDate } from 'app/config/Function'
import { connect } from 'react-redux'
import { CKEditor } from '@ckeditor/ckeditor5-react'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
// import ClassicEditor from 'ckeditor5-build-classic'
import PickerImage from '../../../components/Input/PickerImage'
import {
    MuiPickersUtilsProvider,
    KeyboardDatePicker,
} from '@material-ui/pickers'

import { apiUploadFile } from 'app/apis/Functions/Upload.js'

const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const history = useHistory()

    const [date, setDate] = useState(new Date())

    const handleSubmit = async (event) => {
        const newValue = trimObject(state)
        console.log('newValue', newValue)
        props.showLoading()
        const res = await createPageStatic({
            ...newValue,
            realease_package_id: 1,
            orders: 1,
            status: 1,
            date_publish: convertDate(date),
        })
        props.hideLoading()
        if (res.data.code == 200) {
            history.push('/system/page-static')
            if (res.data.code == 200) {
                toast.success('Tạo tin tức thành công!', {
                    theme: 'colored',
                })
            }
        } else {
            toast.error('Tạo tin tức thất bại!', {
                theme: 'colored',
            })
        }
    }

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

    function uploadPlugin(editor) {
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
            return uploadAdapter(loader)
        }
    }
    function uploadAdapter(loader) {
        return {
            upload: () => {
                return new Promise((resolve, reject) => {
                    const body = new FormData()
                    loader.file.then((file) => {
                        body.append('files', file)
                        apiUploadFile(body)
                            .then((res) => {
                                resolve({
                                    default: res.data.data[0].url,
                                })
                            })
                            .catch((err) => {
                                reject(err)
                            })
                    })
                })
            },
        }
    }

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Danh sách trang tĩnh',
                                path: '/system/page-static',
                            },
                            { name: 'Thêm mới trang tĩnh' },
                        ]}
                    />
                </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="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="Tên trang tĩnh *"
                                    onChange={handleChange}
                                    type="text"
                                    name="name"
                                    value={name || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>

                            <Grid item xs={12} sm={12}>
                                <InputLabel style={{ paddingBottom: '5px' }}>
                                    Nội dung
                                </InputLabel>

                                <CKEditor
                                    style={{
                                        height: 200,
                                    }}
                                    config={{
                                        extraPlugins: [uploadPlugin],
                                    }}
                                    editor={ClassicEditor}
                                    content
                                    onReady={(editor) => {
                                        // You can store the "editor" and use when it is needed.
                                    }}
                                    // value={content}
                                    onChange={(event, editor) => {
                                        const content = editor.getData()
                                        setState({
                                            ...state,
                                            description: content,
                                        })
                                    }}
                                    onBlur={(event, editor) => {}}
                                    onFocus={(event, editor) => {}}
                                />
                            </Grid>
                        </Grid>
                        <Grid
                            container
                            justify={'flex-end'}
                            style={{ marginTop: 20 }}
                        >
                            <Link to="/system/page-static">
                                <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
)
