import React, { useState, useEffect } from 'react'
import {
    ValidatorForm,
    TextValidator,
    SelectValidator,
} from 'react-material-ui-form-validator'
import {
    Button,
    Grid,
    MenuItem,
    FormControlLabel,
    Checkbox,
    Typography,
    RadioGroup,
    Radio,
    IconButton,
    TextField,
    Icon,
    InputAdornment,
} 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,
    replaceItemInArray,
    toPriceVnd,
    toPriceVndInput,
} from 'app/config/Function'
import { connect } from 'react-redux'

import {
    detailProviderSetting,
    updateProviderSetting,
} from 'app/apis/Functions/reconciliation'
import { useTranslation } from 'react-i18next'
import useAuth from 'app/hooks/useAuth'
import { listHour, listMonth, listWeek } from 'app/assets/Data'

const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const location = useLocation()
    const [image, setImage] = useState()
    const { user } = useAuth()
    const [type, setType] = useState('1')
    const [listMoney, setListMoney] = useState([
        {
            condition: 0,
            money: 0,
        },
    ])
    const [listTime, setListTime] = useState([])

    const [date, setDate] = useState(null)
    const { t } = useTranslation()
    useEffect(() => {
        getDataDefault()
    }, [])
    useEffect(() => {
        if (state?.reconciliationCycle) {
            if (state?.reconciliationCycle == 1) setListTime(listHour)
            if (state?.reconciliationCycle == 2) setListTime(listWeek)
            if (state?.reconciliationCycle == 3) setListTime(listMonth)
        }
    }, [state?.reconciliationCycle])

    const history = useHistory()

    const getDataDefault = async () => {
        props.showLoading()
        try {
            const res = await detailProviderSetting(location.state, {})
            if (res.data.data) {
                const {
                    type,
                    reconciliationCycle,
                    reconciliationTime,
                    dataSetting,
                } = res.data.data
                setType(`${type}`)
                if (type == 2 && dataSetting) {
                    const newList = dataSetting.map((e) => {
                        return {
                            condition: e?.value,
                            money: e?.amountOfMoney,
                        }
                    })
                    setListMoney(newList)
                    setState({ ...res.data.data })
                } else {
                    setState({
                        ...res.data.data,
                        percent: dataSetting[0]?.value,
                    })
                }
            }
        } catch (err) {
            toast.error(t(err), {
                theme: 'colored',
            })
        }
        props.hideLoading()
    }

    const handleSubmit = async (event) => {
        const newValue = trimObject(state)
        const listSetting = listMoney.map((e) => {
            return {
                value: e?.condition,
                amountOfMoney: e?.money,
            }
        })
        props.showLoading()
        let res
        if (type == 1) {
            res = await updateProviderSetting({
                idPartner: newValue.idPartner,
                type: parseInt(type),
                reconciliationCycle: newValue?.reconciliationCycle,
                reconciliationTime: newValue?.reconciliationTime,
                dataSetting: [
                    { value: newValue?.percent, amountOfMoney: null },
                ],
            })
        } else {
            res = await updateProviderSetting({
                idPartner: newValue.idPartner,
                type: parseInt(type),
                reconciliationCycle: newValue?.reconciliationCycle,
                reconciliationTime: newValue?.reconciliationTime,
                dataSetting: listSetting,
            })
        }
        props.hideLoading()
        if (res.data.code == 200) {
            history.push('/reconciliation/setting')
            if (res.data.code == 200) {
                toast.success('Cập nhật cấu hình đối soát thành công!', {
                    theme: 'colored',
                })
            }
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const handleChange = (event) => {
        console.log('event.target.name', event.target.name)
        event.persist()

        if (event.target.name == 'reconciliationCycle') {
            setState({
                ...state,
                reconciliationTime: '0',
                [event.target.name]: event.target.value,
            })
        } else {
            setState({
                ...state,
                [event.target.name]: event.target.value,
            })
        }
    }
    const handleChangeList = (event, index) => {
        event.persist()
        if (
            event.target.name == 'condition' ||
            event.target.name == 'money' ||
            event.target.name == 'length'
        ) {
            let inputValue
            if (event.target.name == 'money') {
                inputValue = event.target.value.split('.').join('')
            } else {
                inputValue = event.target.value
            }
            console.log('inputValue', inputValue)
            // Kiểm tra nếu input là số nguyên hoặc số thập phân
            const regex = /^-?\d*\.?\d*$/
            if (regex.test(inputValue)) {
                console.log('run', inputValue)
                let newList = [...listMoney]
                const temp = {
                    ...listMoney[index],
                    [event.target.name]: inputValue,
                }
                newList = replaceItemInArray(newList, index, temp)
                setListMoney(newList)
            } else {
                let newList = [...listMoney]
                setListMoney(newList)
            }
        } else {
            let newList = [...listMoney]
            const temp = {
                ...listMoney[index],
                [event.target.name]: event.target.value,
            }
            newList = replaceItemInArray(newList, index, temp)
            setListMoney(newList)
        }
    }

    const onAdd = () => {
        setListMoney(
            listMoney.concat([
                {
                    condition: 0,
                    money: 0,
                },
            ])
        )
    }

    const deleteTank = (index) => {
        if (listMoney.length > 1) {
            let arr = [...listMoney]
            arr.splice(index, 1)
            setListMoney(arr)
            toast.success('Xoá điều kiện thành công!', {
                theme: 'colored',
            })
        } else {
            toast.warning('Phải có ít nhất một điều kiện!', {
                theme: 'colored',
            })
        }
    }

    const {
        provider_code,
        provider_name,
        phone,
        email,
        merchant_id,
        idPartner,
        reconciliationCycle,
        reconciliationTime,
        percent,
    } = state

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Cấu hình đối soát',
                                path: '/reconciliation/setting',
                            },
                            { 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="Đối tác"
                                    type="text"
                                    name="idPartner"
                                    disabled={true}
                                    value={idPartner || ''}
                                />
                            </Grid>
                            <Grid
                                style={{ alignItems: 'center' }}
                                row
                                item
                                lg={6}
                                md={6}
                                sm={12}
                                xs={12}
                            >
                                <RadioGroup
                                    row
                                    value={type}
                                    onChange={(event) => {
                                        setType(event.target.value)
                                    }}
                                >
                                    <FormControlLabel
                                        value={'1'}
                                        control={<Radio />}
                                        label="Theo %"
                                        style={{
                                            marginRight: 100,
                                        }}
                                    />
                                    <FormControlLabel
                                        value={'2'}
                                        control={<Radio />}
                                        label="Số tiền cố định"
                                    />
                                </RadioGroup>
                            </Grid>

                            {type == '1' ? (
                                <Grid item lg={6} md={6} sm={12} xs={12}>
                                    <TextValidator
                                        variant="outlined"
                                        className="mb-4 w-full"
                                        label="Giá trị (%)"
                                        onChange={handleChange}
                                        type="text"
                                        name="percent"
                                        validators={['isFloat']}
                                        errorMessages={[
                                            'Trường này phải nhập số ',
                                        ]}
                                        value={percent || ''}
                                    />
                                </Grid>
                            ) : (
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                    {listMoney.map((item, index) => (
                                        <Grid
                                            lg={12}
                                            md={12}
                                            sm={12}
                                            xs={12}
                                            container
                                            spacing={3}
                                        >
                                            <Grid
                                                item
                                                lg={5}
                                                md={5}
                                                sm={5}
                                                xs={5}
                                            >
                                                <TextField
                                                    label="Điều kiện"
                                                    fullWidth
                                                    disabled={
                                                        index == 0
                                                            ? true
                                                            : false
                                                    }
                                                    InputProps={{
                                                        style: {
                                                            backgroundColor:
                                                                index == 0
                                                                    ? '#f6f6f6'
                                                                    : '#fff',
                                                        },
                                                        startAdornment: (
                                                            <InputAdornment position="start">
                                                                >=
                                                            </InputAdornment>
                                                        ),
                                                    }}
                                                    variant="outlined"
                                                    name="condition"
                                                    value={
                                                        listMoney[index]
                                                            .condition
                                                    }
                                                    onChange={(event) =>
                                                        handleChangeList(
                                                            event,
                                                            index
                                                        )
                                                    }
                                                />
                                            </Grid>
                                            <Grid
                                                item
                                                lg={5}
                                                md={5}
                                                sm={5}
                                                xs={5}
                                            >
                                                <TextField
                                                    label="Hoa hồng *"
                                                    fullWidth
                                                    name="money"
                                                    value={toPriceVndInput(
                                                        listMoney[index].money
                                                    )}
                                                    variant="outlined"
                                                    InputProps={{
                                                        endAdornment: (
                                                            <InputAdornment position="end">
                                                                VND
                                                            </InputAdornment>
                                                        ),
                                                    }}
                                                    onChange={(event) =>
                                                        handleChangeList(
                                                            event,
                                                            index
                                                        )
                                                    }
                                                />
                                            </Grid>
                                            <Grid
                                                item
                                                lg={2}
                                                md={2}
                                                sm={2}
                                                xs={2}
                                            >
                                                <IconButton
                                                    onClick={() => {
                                                        deleteTank(index)
                                                    }}
                                                    color="error"
                                                >
                                                    <Icon color="error">
                                                        cancel
                                                    </Icon>
                                                </IconButton>
                                            </Grid>
                                        </Grid>
                                    ))}
                                    <Button
                                        onClick={onAdd}
                                        variant="contained"
                                        color="primary"
                                    >
                                        <Icon style={{ color: 'white' }}>
                                            add_circle
                                        </Icon>
                                    </Button>
                                </Grid>
                            )}

                            <Grid xs={6} sm={6} item>
                                <SelectValidator
                                    variant={'outlined'}
                                    label={'Chu kỳ đối soát'}
                                    className="mb-4 w-full"
                                    value={reconciliationCycle || ''}
                                    displayEmpty
                                    name="reconciliationCycle"
                                    onChange={handleChange}
                                >
                                    {[
                                        {
                                            name: 'Hàng ngày',
                                            id: 1,
                                        },
                                        {
                                            name: 'Hàng tuần',
                                            id: 2,
                                        },
                                        {
                                            name: 'Hàng tháng',
                                            id: 3,
                                        },
                                    ].map((e) => (
                                        <MenuItem value={e.id}>
                                            {e.name}
                                        </MenuItem>
                                    ))}
                                </SelectValidator>
                            </Grid>

                            {reconciliationTime && (
                                <Grid xs={6} sm={6} item>
                                    <SelectValidator
                                        variant={'outlined'}
                                        label={'Thời điểm đối soát *'}
                                        className="mb-4 w-full"
                                        value={reconciliationTime || ''}
                                        displayEmpty
                                        name="reconciliationTime"
                                        onChange={handleChange}
                                        validators={['required']}
                                        errorMessages={[
                                            'Không được để trống trường này',
                                        ]}
                                    >
                                        {listTime.map((e) => (
                                            <MenuItem value={e.value}>
                                                {e.name}
                                            </MenuItem>
                                        ))}
                                    </SelectValidator>
                                </Grid>
                            )}
                        </Grid>
                        <Grid
                            style={{ marginTop: 20 }}
                            container
                            justify={'flex-end'}
                        >
                            <Link to="/reconciliation/setting">
                                <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
)
