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 { apiUploadFile } from 'app/apis/Functions/Upload.js'
import {
    detailPageStatic,
    updatePageStatic,
} 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 localStorageService from 'app/services/localStorageService'
import { CKEditor } from '@ckeditor/ckeditor5-react'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import PickerImage from '../../../components/Input/PickerImage'
import {
    MuiPickersUtilsProvider,
    KeyboardDatePicker,
} from '@material-ui/pickers'
const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const [contentState, setContentState] = useState([])
    const history = useHistory()
    const location = useLocation()

    const [date, setDate] = useState()
    useEffect(() => {
        getData()
    }, [])

    const getData = async () => {
        props.showLoading()
        const res = await detailPageStatic(location.state, {})
        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            setState(res.data.data)
            setContentState(res.data.data.description)
            setDate(res.data.data.date_created)
        } else if (res.data.code == 401) {
            localStorageService.removeToken()
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error('Lấy thông tin bản ghi thất bại!', {
                theme: 'colored',
            })
        }
    }

    const handleSubmit = async (event) => {
        const newValue = trimObject(state)
        props.showLoading()
        const res = await updatePageStatic({
            ...newValue,
            description: contentState,
            date_publish: convertDate(date),
        })
        props.hideLoading()
        if (res.data.code == 200) {
            history.push('/system/page-static')
            if (res.data.code == 200) {
                toast.success('Cập nhật tin tức thành công!', {
                    theme: 'colored',
                })
            }
        } else {
            toast.error('Cập nhật tin tức thất bại!', {
                theme: 'colored',
            })
        }
    }

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

    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) => {
                                console.log(res.data.data[0].url)
                                resolve({
                                    default: res.data.data[0].url,
                                })
                            })
                            .catch((err) => {
                                reject(err)
                            })
                    })
                })
            },
        }
    }

    const { code, name } = state

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Danh sách chức năng',
                                path: '/news/category',
                            },
                            { name: 'Thêm mới chức năng' },
                        ]}
                    />
                </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
                                    config={{
                                        extraPlugins: [uploadPlugin],
                                    }}
                                    editor={ClassicEditor}
                                    data={contentState}
                                    onReady={(editor) => {
                                        editor.setData(contentState)
                                        // You can store the "editor" and use when it is needed.
                                    }}
                                    onChange={(event, editor) => {
                                        const content = editor.getData()
                                        setContentState(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">Cập nhật</span>
                            </Button>
                        </Grid>
                    </ValidatorForm>
                </SimpleCard>
            </div>
        </div>
    )
}

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