import React, { useState, useEffect } from 'react'
import {
    CircularProgress,
    Typography,
    FormControlLabel,
    Switch,
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
    Button,
    Stack,
    createTheme,
} from '@mui/material'
import MUIDataTable from 'mui-datatables'
import { chunk } from 'lodash'
import useAuth from 'app/hooks/useAuth'
import { useNavigate } from 'react-router-dom'
import VisibilityIcon from '@mui/icons-material/Visibility'
import { Link } from 'react-router-dom'
import EditIcon from '@mui/icons-material/Edit'
import DeleteIcon from '@mui/icons-material/Delete'
import moment from 'moment'
import CompanyUserService from 'app/services/istar/CompanyUserService'
import { SimpleCard } from 'app/components'
import LockResetIcon from '@mui/icons-material/LockReset'
import { ThemeProvider } from '@mui/system'

const themeee = createTheme({
    components: {
        MUIDataTableBodyCell: {
            styleOverrides: {
                root: {
                    // backgroundColor: '#FFF',
                    // padding: '0.2rem',
                    // maxWidth: '8rem',
                },
            },
        },
        MUIDataTableHeadCell: {
            styleOverrides: {
                root: {
                    // borderColor: '#4061c9',
                    // borderTop: '55px',
                    // backgroundColor: '#2A324C',
                    // color: 'white',
                    // padding: '0px',
                },
            },
        },
    },
})

function CompanyUsers(props) {
    const navigate = useNavigate()
    const [page, setPage] = useState(0)
    const [count, setCount] = useState(1)
    const [data, setData] = useState([['Loading Data...']])
    const [isLoading, setIsLoading] = useState(false)
    const [openDialogue, setOpenDialogue] = React.useState(false)
    const [deleteId, setDeleteId] = React.useState('')

    const handleClose = () => {
        setDeleteId('')
        setOpenDialogue(false)
    }

    const handleClickOpen = (e, id) => {
        e.preventDefault()

        console.log('ID: ', id)
        setDeleteId(id)
        setOpenDialogue(true)
    }

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

    const getData = () => {
        setIsLoading(true)
        CompanyUserService.query({ search: '', page: page, pageSize: 5 })
            .then((res) => {
                console.log('RES: ', res)
                setData(res.data)
                setIsLoading(false)
                setCount(res.total)
            })
            .catch((err) => console.log('ERR:', err))
    }

    // mock async function
    const xhrRequest = ({ page = 0, pageSize = 5, sortOrder, search }) => {
        return new Promise((resolve, reject) => {
            CompanyUserService.query({ search, page, pageSize, sortOrder })
                .then((res) => {
                    resolve({
                        data: res.data,
                        total: res.total,
                    })
                })
                .catch((err) => console.log('ERR:', err))
        })
    }

    const changePage = (tableState) => {
        setIsLoading(true)
        xhrRequest({
            page: tableState.page,
            pageSize: tableState.rowsPerPage,
            sortOrder: tableState.sortOrder,
            search: tableState.searchText,
        }).then((res) => {
            setData(res.data)
            setIsLoading(false)
            setPage(tableState.page)
            setCount(res.total)
        })
    }

    const handleChange = (e, tableMeta) => {
        const id = data[tableMeta.rowIndex]._id
        CompanyUserService.updateRecord(id, {
            isBlocked: e.target.value === 'Yes' ? false : true,
        })
            .then((res) => {
                getData()
            })
            .catch((err) => console.log('ERROR', err))
    }
    const handleKeoskChange = (e, tableMeta) => {
        const id = data[tableMeta.rowIndex]._id
        CompanyUserService.updateRecord(id, {
            keoskMode: e.target.value === 'Yes' ? false : true,
        })
            .then((res) => {
                getData()
            })
            .catch((err) => console.log('ERROR', err))
    }

    const columns = [
        {
            name: 'name',
            label: 'Name',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'email',
            label: 'Email',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'phoneNumber',
            label: 'Phone Number',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'country',
            label: 'Country',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'copmany',
            label: 'Company',
            options: {
                // filter: true,
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <>
                            <p>{data[tableMeta.rowIndex]?.company?.name}</p>
                        </>
                    )
                },
            },
        },
        {
            name: 'isBlocked',
            label: 'Is Blocked?',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <FormControlLabel
                            label={value ? 'Yes' : 'No'}
                            value={value ? 'Yes' : 'No'}
                            control={
                                <Switch
                                    color="primary"
                                    checked={value}
                                    value={value ? 'Yes' : 'No'}
                                />
                            }
                            onChange={(event) => {
                                console.log('TABLE META: ', tableMeta)
                                handleChange(event, tableMeta)
                                updateValue(
                                    event.target.value === 'Yes' ? false : true
                                )
                            }}
                        />
                    )
                },
            },
        },

        {
            name: 'keoskMode',
            label: 'Keosk Mode',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <FormControlLabel
                            label={value ? 'Yes' : 'No'}
                            value={value ? 'Yes' : 'No'}
                            control={
                                <Switch
                                    color="primary"
                                    checked={value}
                                    value={value ? 'Yes' : 'No'}
                                />
                            }
                            onChange={(event) => {
                                console.log('TABLE META: ', tableMeta)
                                handleKeoskChange(event, tableMeta)
                                updateValue(
                                    event.target.value === 'Yes' ? false : true
                                )
                            }}
                        />
                    )
                },
            },
        },

        {
            name: 'Change Password',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <>
                            <Button
                                variant="contained"
                                onClick={(e) =>
                                    navigate(
                                        '/admin/company-users/change-password/' +
                                            data[tableMeta.rowIndex]._id
                                    )
                                }
                            >
                                <LockResetIcon />
                            </Button>
                        </>
                    )
                },
            },
        },

        {
            name: 'Actions',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <>
                            <Link
                                to={`/admin/company-users/edit/${
                                    data[tableMeta.rowIndex]._id
                                }`}
                                title="Edit Company User"
                            >
                                <EditIcon />
                            </Link>

                            <Link
                                to="#"
                                title="Delete Company User"
                                onClick={(e) =>
                                    handleClickOpen(
                                        e,
                                        data[tableMeta.rowIndex]._id
                                    )
                                }
                            >
                                <DeleteIcon />
                            </Link>
                        </>
                    )
                },
            },
        },
    ]

    const handleMultipleDelete = (action) => {
        setIsLoading(true)
        // data[tableMeta.rowIndex]._id
        console.log('action: ', action)

        let newArr = action?.data?.map((d) => {
            return data[d?.index]?._id
        })
        console.log('NEW ARR: ', newArr)
        CompanyUserService.multipleDelete({
            deleteItems: newArr,
        })
            .then((res) => {
                console.log(res)
                getData()
            })
            .catch((err) => console.log(err))
            .finally(() => {
                setIsLoading(false)
            })
    }

    const options = {
        responsive: 'standard',
        fixedHeader: true,
        fixedSelectColumn: false,
        // filters: false,
        filter: false,
        // filterType: 'dropdown',

        jumpToPage: true,
        rowsPerPage: 5,
        rowsPerPageOptions: [5],
        // selectableRows: 'none',
        download: false,
        print: false,
        serverSide: true,
        count, // Use total number of items
        // count: -1, // Unknown number of items
        page,
        onTableChange: (action, tableState) => {
            console.log(action, tableState)
            if (action === 'changePage') {
                console.log('Go to page', tableState.page)
                changePage(tableState)
            } else if (action == 'sort') {
                changePage(tableState)
            } else if (action == 'search') {
                changePage(tableState)
            }
        },
        onRowsDelete: (action, tableState) => {
            // console.log(action, tableState)
            handleMultipleDelete(action)
        },
    }
    return (
        <>
            <SimpleCard>
                <div className="container">
                    <ThemeProvider theme={themeee}>
                        <MUIDataTable
                            title={
                                <Stack spacing={2} direction="row">
                                    <Typography variant="h6">
                                        Company Users
                                        {isLoading && (
                                            <CircularProgress
                                                size={24}
                                                style={{
                                                    marginLeft: 15,
                                                    position: 'relative',
                                                    top: 4,
                                                }}
                                            />
                                        )}
                                    </Typography>
                                    <Button
                                        variant="contained"
                                        onClick={() =>
                                            navigate('/admin/company-users/add')
                                        }
                                    >
                                        Add Company User
                                    </Button>
                                </Stack>
                            }
                            data={data}
                            columns={columns}
                            options={options}
                        />
                    </ThemeProvider>
                </div>
            </SimpleCard>
            <div>
                <Dialog
                    open={openDialogue}
                    onClose={handleClose}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                >
                    <DialogTitle id="alert-dialog-title">
                        Confirmation
                    </DialogTitle>
                    <DialogContent>
                        <DialogContentText id="alert-dialog-description">
                            To delete this, click confirm. Or click on cancel
                            button to cancel
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose} color="primary">
                            Cancel
                        </Button>
                        <Button
                            onClick={() => {
                                handleClose()
                                CompanyUserService.deleteRecord(deleteId)
                                    .then((res) => {
                                        getData()
                                        console.log(
                                            'Successfullly deleted',
                                            res
                                        )
                                    })
                                    .catch((err) => {
                                        console.log('ERROR', err)
                                    })
                            }}
                            color="primary"
                        >
                            Confirm
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        </>
    )
}
export default CompanyUsers
