import React, { useState, useEffect } from 'react'
import {
    ValidatorForm,
    TextValidator,
    SelectValidator,
} from 'react-material-ui-form-validator'
import {
    Button,
    Grid,
    MenuItem,
    FormControlLabel,
    Checkbox,
    Typography,
    FormControl,
    InputLabel,
    Select,
} from '@material-ui/core'
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,
    encryString,
    convertDate,
    convertTimeApi,
} from 'app/config/Function'
import { connect } from 'react-redux'
import PieChartReport from './PieChartReport'
import LineChartCustom from './LineChartCustom'
import TabTrans from './TabTrans/index'

import {
    detailSupplier,
    updateSupplier,
    piechartPaymentPartner,
    linechartPaymentPartner,
} from 'app/apis/Functions/supplier'
import { useTranslation } from 'react-i18next'
import useAuth from 'app/hooks/useAuth'
const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const location = useLocation()
    const [image, setImage] = useState()
    const { user } = useAuth()
    const [type, setType] = useState(1)
    const [day, setDay] = useState(7)
    const [dataPieChart, setDataPieChart] = useState()
    const [dataLineChart, setDataLineChart] = useState()
    const color = ['#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00']
    const [date, setDate] = useState(null)
    const { t } = useTranslation()
    useEffect(() => {
        getDataDefault()
    }, [])

    useEffect(() => {
        if (day && type) {
            getDataLineChart()
            getDataPieChart()
        }
    }, [day, type])

    const history = useHistory()

    const getDataDefault = async () => {
        props.showLoading()
        try {
            const res = await detailSupplier(location.state?.id, {})
            setState({ ...res.data.data })
        } catch (err) {
            toast.error(t(err), {
                theme: 'colored',
            })
        }
        props.hideLoading()
    }

    const getDataLineChart = async () => {
        props.showLoading()
        try {
            const res = await linechartPaymentPartner({
                id: location.state?.provider_code,
                type: type,
                dayCount: day,
            })
            console.log('res', res.data)
            if (res.data.code == 200 && res.data.data) {
                const xAxis = res.data.data?.map((e) => {
                    return e?.Day
                })
                const series = res.data.data?.map((e) => {
                    return e?.Value
                })

                setDataLineChart({
                    xAxis,
                    series,
                })
            } else {
                setDataLineChart(null)
            }
        } catch (err) {
            toast.error(t(err), {
                theme: 'colored',
            })
        }
        props.hideLoading()
    }
    const getDataPieChart = async () => {
        props.showLoading()
        try {
            const res = await piechartPaymentPartner({
                id: location.state?.provider_code,
                type: type,
                dayCount: day,
            })
            if (res.data.code == 200 && res.data.data) {
                const { Reconciled, NotReconciled } = res.data.data

                setDataPieChart([
                    {
                        value: Reconciled,
                        name: 'Đã đối soát',
                    },
                    {
                        value: NotReconciled,
                        name: 'Khác',
                    },
                ])
            }
        } catch (err) {
            toast.error(t(err), {
                theme: 'colored',
            })
        }
        props.hideLoading()
    }

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

        props.showLoading()
        const res = await updateSupplier({
            ...newValue,
        })
        console.log(res)
        props.hideLoading()
        if (res.data.code == 200) {
            history.push('/payment-supplier')
            if (res.data.code == 200) {
                toast.success('Cập nhật đối tác thanh toán thành công!', {
                    theme: 'colored',
                })
            }
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

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

    console.log('dataLineChart', dataLineChart)

    const { provider_code, provider_name, phone, email, address } = state
    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Đối tác thanh toán',
                                path: '/payment-supplier',
                            },
                            { name: 'Chi tiết' },
                        ]}
                    />
                </div>
                <SimpleCard>
                    <ValidatorForm onSubmit={handleSubmit} onError={() => null}>
                        <Grid container spacing={3}>
                            <Grid xs={4} item>
                                <div
                                    style={{
                                        display: 'flex',
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                        height: '100%',
                                    }}
                                >
                                    <img
                                        src={
                                            'https://image.bnews.vn/MediaUpload/Org/2022/04/26/logo-bidv-20220426071253.jpg'
                                        }
                                        style={{
                                            width: 150,
                                            height: 150,
                                            backgroundColor: '#000',
                                            borderRadius: 75,
                                        }}
                                    />
                                </div>
                            </Grid>
                            <Grid xs={8} item container>
                                <Grid container spacing={3}>
                                    <Grid item lg={6} md={6} sm={12} xs={12}>
                                        <TextValidator
                                            variant="outlined"
                                            className="mb-4 w-full"
                                            label="Mã đối tác *"
                                            onChange={handleChange}
                                            type="text"
                                            name="provider_code"
                                            disabled={true}
                                            value={provider_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 đối tác *"
                                            onChange={handleChange}
                                            disabled={true}
                                            type="text"
                                            name="provider_name"
                                            value={provider_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="Số điện thoại *"
                                            onChange={handleChange}
                                            disabled={true}
                                            type="text"
                                            name="phone"
                                            value={phone || ''}
                                            validators={[
                                                'required',
                                                'isNumber',
                                                'minStringLength:10',
                                                'maxStringLength:15',
                                            ]}
                                            errorMessages={[
                                                'Không được để trống trường này',
                                                'Trường này phải nhập số ',
                                                'Số điện thoại phải có ít nhất 10 chữ số',
                                                'Số điện thoại nhiều nhất chỉ có 15 chữ số',
                                            ]}
                                        />
                                    </Grid>
                                    <Grid item lg={6} md={6} sm={12} xs={12}>
                                        <TextValidator
                                            variant="outlined"
                                            className="mb-4 w-full"
                                            label="Email *"
                                            onChange={handleChange}
                                            disabled={true}
                                            type="text"
                                            name="email"
                                            value={email || ''}
                                            validators={['required', 'isEmail']}
                                            errorMessages={[
                                                'Không được để trống trường này',
                                                'Email không hợp lệ',
                                            ]}
                                        />
                                    </Grid>
                                    <Grid item lg={12} md={12} sm={12} xs={12}>
                                        <TextValidator
                                            variant="outlined"
                                            className="mb-4 w-full"
                                            label="Địa chỉ"
                                            onChange={handleChange}
                                            disabled={true}
                                            type="text"
                                            name="address"
                                            value={address || ''}
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                    </ValidatorForm>
                </SimpleCard>
                <div style={{ height: 10 }} />
                <SimpleCard>
                    <Grid container spacing={2}>
                        <Grid
                            item
                            lg={12}
                            md={12}
                            sm={12}
                            xs={12}
                            container
                            justify={'flex-end'}
                            spacing={3}
                        >
                            <Grid item lg={2} md={2} sm={4} xs={4}>
                                {type && (
                                    <FormControl variant="outlined" fullWidth>
                                        <Select
                                            value={type}
                                            onChange={(e) => {
                                                setType(e.target.value)
                                            }}
                                            inputProps={{
                                                name: 'age',
                                                id: 'outlined-age-native-simple',
                                            }}
                                        >
                                            {[
                                                {
                                                    name: 'Theo số hoa hồng',
                                                    value: 1,
                                                },
                                                {
                                                    name: 'Theo giao dịch',
                                                    value: 2,
                                                },
                                            ].map((e) => (
                                                <MenuItem value={e.value}>
                                                    {e.name}
                                                </MenuItem>
                                            ))}
                                        </Select>
                                    </FormControl>
                                )}
                            </Grid>
                            <Grid item lg={2} md={2} sm={4} xs={4}>
                                <FormControl variant="outlined" fullWidth>
                                    {day && (
                                        <Select
                                            value={day}
                                            onChange={(e) => {
                                                setDay(e.target.value)
                                            }}
                                            inputProps={{
                                                name: 'age',
                                                id: 'outlined-age-native-simple',
                                            }}
                                        >
                                            {[
                                                {
                                                    name: '7 ngày',
                                                    value: 7,
                                                },
                                                {
                                                    name: '14 ngày',
                                                    value: 14,
                                                },
                                                {
                                                    name: '30 ngày',
                                                    value: 30,
                                                },
                                                // {
                                                //     name: '90 ngày',
                                                //     value: 90,
                                                // },
                                                // {
                                                //     name: '180 ngày',
                                                //     value: 180,
                                                // },
                                                // {
                                                //     name: '1 năm',
                                                //     value: 365,
                                                // },
                                            ].map((e) => (
                                                <MenuItem value={e.value}>
                                                    {e.name}
                                                </MenuItem>
                                            ))}
                                        </Select>
                                    )}
                                </FormControl>
                            </Grid>
                        </Grid>
                        <Grid xs={3} item>
                            {dataPieChart && (
                                <PieChartReport data={dataPieChart} />
                            )}
                        </Grid>

                        <Grid xs={9} item>
                            {dataPieChart && (
                                <LineChartCustom
                                    color={color}
                                    data={dataLineChart}
                                />
                            )}
                        </Grid>
                    </Grid>
                </SimpleCard>

                <div style={{ height: 10 }} />
                <SimpleCard>
                    <TabTrans />
                </SimpleCard>

                <Grid style={{ marginTop: 20 }} container justify={'flex-end'}>
                    <Link to="/payment-supplier">
                        <Button
                            style={{
                                marginRight: 20,
                            }}
                            color="inherit"
                            variant="contained"
                            onClick={() => {}}
                        >
                            <span className="capitalize">Quay lại</span>
                        </Button>
                    </Link>
                </Grid>
            </div>
        </div>
    )
}

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