import React, { useState, useEffect } from 'react'
import {
    ValidatorForm,
    TextValidator,
    SelectValidator,
} from 'react-material-ui-form-validator'
import {
    Button,
    Grid,
    MenuItem,
    Typography,
    IconButton,
    Icon,
    Tooltip,
} from '@material-ui/core'
import _ from 'lodash'
import {
    createGasStation,
    detailGasStation,
    deleteGasField,
    deleteGasOnline,
    changeStatusStore,
} from 'app/apis/Functions/merchant'
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 } from 'app/config/Function'
import { connect } from 'react-redux'
import { dropdownMerchant } from 'app/apis/Functions/dropdown'
import Table from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableContainer from '@material-ui/core/TableContainer'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import Paper from '@material-ui/core/Paper'
import { convertDate } from 'app/config/Function'
import { useTranslation } from 'react-i18next'
import AcceptStore from 'app/components/dialog/AcceptStore'
import RejectStore from 'app/components/dialog/RejectStore'

const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const history = useHistory()
    const [listDrop, setListDrop] = useState([])
    const [openCreate, setOpenCreate] = useState(false)
    const [listField, setListField] = useState([])
    const [fountainSelected, setFountainSelected] = useState()
    const [openUpdate, setOpenUpdate] = useState()
    const [listProvince, setListProvince] = useState([])
    const [openAccept, setOpenAccpet] = useState(false)
    const [openReject, setOpenReject] = useState(false)
    const location = useLocation()
    const { t } = useTranslation()
    useEffect(() => {
        getDateDetail()
        getData()
    }, [])

    const getDateDetail = async () => {
        props.showLoading()
        const res = await detailGasStation(location.state, {})
        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            console.log(res.data.data.GasFueldInfo)
            if (res.data.data.GasFueldInfo) {
                setListField(res.data.data?.GasFueldInfo)
            }

            setState(res.data.data)
        } else if (res.data.code == 401) {
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const getData = async () => {
        props.showLoading()
        const res = await dropdownMerchant({})
        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            const newList = res.data.data.map((e) => {
                return { ...e, name: e.merchant_name }
            })

            setListDrop(newList)
        } else if (res.data.code == 401) {
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error('Lấy giữ liệu thất bại !', {
                theme: 'colored',
            })
        }
    }

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

        props.showLoading()
        const res = await createGasStation({
            id: newValue?.id,
            merchant_id: newValue?.merchant_id,
            store_name: newValue?.store_name,
            address: newValue?.address,
            gas_fields: listField,
            store_code: newValue?.store_code,
            queue_name: newValue?.queue_name,

            account: newValue?.account,
            user_name: newValue?.user_name,
            password: newValue?.password,
        })
        props.hideLoading()
        if (res.data.code == 200) {
            history.push('/gas-station')
            if (res.data.code == 200) {
                toast.success('Cập nhật cây xăng 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,
        })
    }

    const handleDateChange = (date) => {
        setState({ ...state, date })
    }

    const countFountain = () => {
        let temp = 0

        listField.map((e) => {
            if (e.gas_olines) {
                temp += e.gas_olines.length
            }
        })

        return temp
    }

    const changeSatusStore = async (status) => {
        if (location.state) {
            props.showLoading()
            const res = await changeStatusStore({
                id: location.state,
                status: status,
            })
            props.hideLoading()
            if (res.data.code == 200) {
                toast.success(
                    `${
                        status == 4 ? 'Từ chối phê duyệt' : 'Phê duyệt'
                    } cây xăng thành công`,
                    {
                        theme: 'colored',
                    }
                )
                history.push('/gas-station')
            } else {
                toast.error(t(res.data.error), {
                    theme: 'colored',
                })
            }
        } else {
            toast.error('Trạng thái không hợp lệ', {
                theme: 'colored',
            })
        }
    }

    const acceptStoreSub = async (forever, date) => {
        setOpenAccpet(false)
        props.showLoading()
        const res = await changeStatusStore({
            id: location.state,
            status: 1,
            expired: forever ? null : convertDate(date),
        })
        props.hideLoading()
        if (res.data.code == 200) {
            toast.success(`${'Phê duyệt'} cây xăng thành công`, {
                theme: 'colored',
            })
            history.push('/gas-station')
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const rejectStoreSub = async (reason) => {
        setOpenReject(false)
        props.showLoading()
        const res = await changeStatusStore({
            id: location.state,
            status: 4,
            reason: reason,
        })
        props.hideLoading()
        if (res.data.code == 200) {
            toast.success(`${'Từ chối'} cây xăng thành công`, {
                theme: 'colored',
            })
            history.push('/gas-station')
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const {
        store_name,
        province_id,
        supplier_main,
        address,
        partition_id,
        store_code,
        phone,
        email,
        merchant_id,
        provice_name,
        status,
        supplier_main_name,
        partition_name,
        merchant_name,
    } = state

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Danh sách cây xăng',
                                path: '/gas-station',
                            },
                            { name: 'Chi tiết' },
                        ]}
                    />
                </div>
                <SimpleCard>
                    <ValidatorForm
                        id="form-create"
                        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="Thuộc pháp nhân "
                                    disabled={true}
                                    onChange={handleChange}
                                    type="text"
                                    name="merchant_name"
                                    value={merchant_name || ''}
                                />
                            </Grid>

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Mã cây xăng "
                                    disabled={true}
                                    onChange={handleChange}
                                    type="text"
                                    name="store_code"
                                    value={store_code || ''}
                                />
                            </Grid>

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tên cây xăng "
                                    onChange={handleChange}
                                    type="text"
                                    name="store_name"
                                    value={store_name || ''}
                                    disabled={true}
                                />
                            </Grid>

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tỉnh thành phố "
                                    onChange={handleChange}
                                    type="text"
                                    name="provice_name"
                                    value={provice_name || ''}
                                    disabled={true}
                                />
                            </Grid>

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Địa chỉ "
                                    onChange={handleChange}
                                    type="text"
                                    name="address"
                                    value={address || ''}
                                    disabled={true}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Vùng "
                                    onChange={handleChange}
                                    type="text"
                                    name="partition_name"
                                    value={partition_name || ''}
                                    disabled={true}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Đơn vị cung cấp main "
                                    onChange={handleChange}
                                    type="text"
                                    name="supplier_main_name"
                                    value={supplier_main_name || ''}
                                    disabled={true}
                                />
                            </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}
                                    type="text"
                                    name="phone"
                                    value={phone || ''}
                                    disabled={true}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Email "
                                    onChange={handleChange}
                                    type="text"
                                    name="email"
                                    value={email || ''}
                                    disabled={true}
                                />
                            </Grid>

                            <Grid
                                item
                                container
                                lg={12}
                                md={12}
                                sm={12}
                                xs={12}
                                justify="space-between"
                                style={{
                                    padding: 10,
                                    borderRadius: 5,
                                }}
                            >
                                <Typography variant="h6">
                                    Thông tin trụ xăng
                                </Typography>

                                <Grid
                                    item
                                    container
                                    lg={12}
                                    md={12}
                                    sm={12}
                                    xs={12}
                                    justify="space-between"
                                >
                                    <div>
                                        <Typography variant="subtitle1">
                                            Số lượng trụ: {listField.length}
                                        </Typography>
                                        <Typography variant="subtitle1">
                                            Số lượng vòi: {countFountain()}
                                        </Typography>
                                    </div>
                                </Grid>

                                {listField.map((item, index) => (
                                    <Grid
                                        style={{
                                            border: '1px solid #B9B9B9',
                                            borderRadius: 5,
                                            padding: 10,
                                            marginTop: 20,
                                        }}
                                        lg={12}
                                        md={12}
                                        sm={12}
                                        xs={12}
                                    >
                                        <Grid lg={12} md={12} sm={12} xs={12}>
                                            <div
                                                style={{
                                                    alignItems: 'center',
                                                    justifyContent:
                                                        'space-between',
                                                    display: 'flex',
                                                    marginBottom: 10,
                                                }}
                                            >
                                                <Typography variant="h6">
                                                    {item.field_name}
                                                </Typography>
                                            </div>

                                            <TableContainer component={Paper}>
                                                <Table aria-label="simple table">
                                                    <TableHead>
                                                        <TableRow
                                                            style={{
                                                                backgroundColor:
                                                                    '#F3F3F3',
                                                            }}
                                                        >
                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                    width: 100,
                                                                }}
                                                                align="center"
                                                            >
                                                                STT
                                                            </TableCell>

                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                }}
                                                                align="center"
                                                            >
                                                                Mã vòi
                                                            </TableCell>
                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                }}
                                                                align="center"
                                                            >
                                                                Vòi
                                                            </TableCell>
                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                }}
                                                                align="center"
                                                            >
                                                                Bồn kết nối
                                                            </TableCell>
                                                        </TableRow>
                                                    </TableHead>
                                                    <TableBody>
                                                        {item?.gas_olines.map(
                                                            (row, index) => (
                                                                <TableRow
                                                                    key={
                                                                        row.name
                                                                    }
                                                                >
                                                                    <TableCell
                                                                        component="th"
                                                                        scope="row"
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="center"
                                                                    >
                                                                        {index +
                                                                            1}
                                                                    </TableCell>
                                                                    <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.code
                                                                        }
                                                                    </TableCell>
                                                                    <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.name
                                                                        }
                                                                    </TableCell>

                                                                    <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.tank_name
                                                                        }
                                                                    </TableCell>
                                                                </TableRow>
                                                            )
                                                        )}
                                                    </TableBody>
                                                </Table>
                                            </TableContainer>
                                        </Grid>
                                    </Grid>
                                ))}
                            </Grid>
                        </Grid>
                        <Grid
                            style={{
                                marginTop: 40,
                            }}
                            container
                            justify={'flex-end'}
                        >
                            <Button
                                style={{
                                    marginRight: 20,
                                }}
                                color="inherit"
                                variant="contained"
                                onClick={() => {
                                    history.goBack()
                                }}
                            >
                                <span className="capitalize">Quay lại</span>
                            </Button>
                            {status == 3 && (
                                <Button
                                    style={{
                                        marginRight: 20,
                                    }}
                                    color="secondary"
                                    variant="contained"
                                    onClick={() => {
                                        setOpenReject(true)
                                    }}
                                >
                                    <span
                                        style={{
                                            color: 'white',
                                        }}
                                        className="capitalize"
                                    >
                                        Từ chối
                                    </span>
                                </Button>
                            )}

                            {status == 3 && (
                                <Button
                                    color="primary"
                                    variant="contained"
                                    onClick={() => {
                                        setOpenAccpet(true)
                                    }}
                                >
                                    <span className="capitalize">Duyệt</span>
                                </Button>
                            )}

                            <AcceptStore
                                open={openAccept}
                                handleClose={() => {
                                    setOpenAccpet(false)
                                }}
                                onAgree={(forever, date) => {
                                    acceptStoreSub(forever, date)
                                }}
                            />

                            <RejectStore
                                open={openReject}
                                handleClose={() => {
                                    setOpenReject(false)
                                }}
                                onAgree={(reason) => {
                                    rejectStoreSub(reason)
                                }}
                            />
                        </Grid>
                    </ValidatorForm>
                </SimpleCard>
            </div>
        </div>
    )
}

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