import React, { useState, useEffect } from 'react'
import ToolUserView from './View'
import {
    getListGasStation,
    deleteGasStation,
    changeStatusGasStation,
    changeStatusStore,
} from 'app/apis/Functions/merchant'
import { useHistory } from 'react-router-dom'
import KEY from 'app/assets/Key'
import { connect } from 'react-redux'
import { showLoading, hideLoading } from 'app/redux/actions/loadingAction'
import { toast } from 'react-toastify'
import useDebounce from 'app/hooks/useDebounce'
import { dropdownMerchant } from 'app/apis/Functions/dropdown'
import { useTranslation } from 'react-i18next'
import { dropdownStoreStatus } from 'app/apis/Functions/dropdown'
import { convertDate } from 'app/config/Function'

const ToolNotificate = (props) => {
    const [txtSearch, setTxtSearch] = useState('')
    const searchDebount = useDebounce(txtSearch, 1000)
    const { t } = useTranslation()
    const [activeSelected, setActiveSeleted] = useState(null)
    const [changeActive, setChangeActive] = useState(1)
    const [status, setStatus] = useState()
    const [pageIndex, setPageIndex] = useState(0)
    const [pageSize] = useState(10)
    const [totalRecords, setTotalRecord] = useState(0)
    const [listMerchant, setListMerchant] = useState([])
    const [merchant, setMerchant] = useState()
    const [listStatus, setListStatus] = useState([])
    const history = useHistory()

    const [data, setData] = useState([])
    const [permissions, setPermissions] = useState([])
    useEffect(() => {
        getDropDownMerchant()
        getDropdownData()
    }, [])

    const handeChangeActive = async (id, status_id) => {
        props.showLoading()
        const res = await changeStatusGasStation({
            idGuid: id,
            status: status_id,
        })
        props.hideLoading()
        if (res.data.code == 200) {
            getData()
            toast.success('Thay đổi trạng thái thành công!', {
                theme: 'colored',
            })
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const getData = async (isInit) => {
        props.showLoading()
        let res
        if (isInit) {
            setPageIndex(0)
            res = await getListGasStation({
                text_search: searchDebount,
                page_no: 0,
                page_size: pageSize,
                merchant_id: merchant,
                status,
            })
        } else {
            res = await getListGasStation({
                text_search: searchDebount,
                page_no: pageIndex + 1,
                page_size: pageSize,
                merchant_id: merchant,
                status,
            })
        }

        props.hideLoading()

        if (res.data.code == 200 && res.data.data) {
            console.log(res.data)
            const newList = res.data.data.data.map((e, i) => {
                return {
                    ...e,
                    index: i + 1 + pageIndex * pageSize,
                    date_expried: e?.expired ? e?.expired.substring(0, 10) : '',
                    field: `${e?.total_fueld} trụ \n${e?.total_gas} vòi`,
                }
            })

            setData(newList)
            setTotalRecord(res.data.data.total_elements)
        } else if (res.data.code == 401) {
            localStorage.removeItem(KEY.API_TOKEN)
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const getDropdownData = async () => {
        const res = await dropdownStoreStatus()
        if (res.data.code == 200 && res.data.data) {
            setListStatus(res.data.data)
        } else {
            toast.error('Lấy giữ liệu thất bại !', {
                theme: 'colored',
            })
        }
    }

    const getDropDownMerchant = async () => {
        try {
            const res = await dropdownMerchant()
            console.log(res)
            const newList = res.data.data.map((e) => {
                return { ...e, name: e.merchant_name }
            })
            setListMerchant(newList)
        } catch (err) {
            //toast.error(t(err))
        }
    }

    useEffect(() => {
        getData(false)
    }, [pageIndex])

    useEffect(() => {
        getData(true)
    }, [searchDebount, merchant, status])

    const removeItem = async (item) => {
        props.showLoading()
        let res

        if (item.status == 1) {
            res = await changeStatusStore({
                id: item.id,
                status: 5,
            })
        } else {
            res = await changeStatusStore({
                id: item.id,
                status: 1,
            })
        }

        props.hideLoading()
        if (res.data.code == 200) {
            getData(true)
            toast.success('Cập nhật trạng thái cây xăng thành công!', {
                theme: 'colored',
            })
        } else if (res.data.code == 401) {
            localStorage.removeItem(KEY.API_TOKEN)
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const acceptStoreSub = async (item, forever, date) => {
        props.showLoading()
        const res = await changeStatusStore({
            id: item.id,
            status: item?.status == 3 ? 0 : 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',
            })
            getData()
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const acceptUpdateTime = async (item, forever, date) => {
        props.showLoading()
        const res = await changeStatusStore({
            id: item.id,
            status: item.status,
            expired: forever ? null : convertDate(date),
        })
        props.hideLoading()
        if (res.data.code == 200) {
            toast.success(
                `${'Điều chỉnh thời gian hoạt động của'} cây xăng thành công`,
                {
                    theme: 'colored',
                }
            )
            getData()
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    return (
        <ToolUserView
            data={data}
            removeItem={removeItem}
            setTxtSearch={setTxtSearch}
            setActiveSeleted={setActiveSeleted}
            pageIndex={pageIndex}
            changeActive={changeActive}
            setChangeActive={setChangeActive}
            setPageIndex={setPageIndex}
            activeSelected={activeSelected}
            handeChangeActive={handeChangeActive}
            totalRecords={totalRecords}
            permissions={permissions}
            listMerchant={listMerchant}
            merchant={merchant}
            setMerchant={setMerchant}
            status={status}
            setStatus={setStatus}
            listStatus={listStatus}
            acceptStoreSub={acceptStoreSub}
            acceptUpdateTime={acceptUpdateTime}
        />
    )
}

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