import React, { useState, useEffect } from 'react'
import {
    CircularProgress,
    Typography,
    FormControlLabel,
    Switch,
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
    Button,
    Stack,
    createTheme,
    InputLabel,
    FormControl,
    Select,
    MenuItem,
} from '@mui/material'
import MUIDataTable from 'mui-datatables'
import { chunk } from 'lodash'
import useAuth from 'app/hooks/useAuth'
import { useLocation, 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 UserGuestsService from 'app/services/istar/UserGuestsService'
import { SimpleCard } from 'app/components'
import { ThemeProvider } from '@mui/system'
import CompanyService from 'app/services/istar/CompanyService'

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 UserGuests(props) {
    const navigate = useNavigate()
    const location = useLocation()
    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 [companies, setCompanies] = React.useState([])
    const [filter, setFilter] = React.useState('')

    React.useEffect(() => {
        CompanyService.getAllRecords().then((res) => {
            setCompanies(res)
        })
    }, [])

    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)
        UserGuestsService.query({
            search: '',
            page: 0,
            pageSize: 5,
            filter: 'all',
        })
            .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,
        filterValue = 'all',
    }) => {
        return new Promise((resolve, reject) => {
            UserGuestsService.query({
                search,
                page,
                pageSize,
                sortOrder,
                filter: filterValue,
            })
                .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 handleFilterChange = (event) => {
        setFilter(event.target.value)
        let filterValue = event.target.value
        xhrRequest({
            search: '',
            page: 0,
            pageSize: 5,
            filterValue,
        }).then((res) => {
            // console.log('RES DATA: ', res.data)
            setData(res.data)
            setIsLoading(false)
            setCount(res.total)
        })
    }

    const columns = [
        {
            name: 'responses',
            label: 'Responses',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <Button
                            variant="contained"
                            color="primary"
                            onClick={() => {
                                navigate(
                                    '/admin/customer-responses/' +
                                        data[tableMeta.rowIndex]._id,
                                    {
                                        state: {
                                            data: data[tableMeta.rowIndex],
                                            prevPath: location.pathname,
                                        },
                                    }
                                )
                            }}
                        >
                            View
                        </Button>
                    )
                },
            },
        },
        {
            name: 'email',
            label: 'Email',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'firstName',
            label: 'Name',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <p>
                            {data[tableMeta.rowIndex].firstName}{' '}
                            {data[tableMeta.rowIndex].lastName}
                        </p>
                    )
                },
            },
        },
        {
            name: 'address',
            label: 'Address',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'phone',
            label: 'Phone',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'gender',
            label: 'Gender',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'state',
            label: 'State',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'yearOfBirth',
            label: 'Year Of Birth',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'company',
            label: 'Company',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return <p>{data[tableMeta.rowIndex].company?.name}</p>
                },
            },
        },
        {
            name: 'createdAt',
            label: 'Time & Date',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <p>
                            {moment(data[tableMeta.rowIndex].createdAt).format(
                                'YYYY-MM-DD HH:mm'
                            )}
                        </p>
                    )
                },
            },
        },

        {
            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 Record"
                                onClick={(e) =>
                                    handleClickOpen(
                                        e,
                                        data[tableMeta.rowIndex]._id
                                    )
                                }
                            >
                                <DeleteIcon />
                            </Link>
                        </>
                    )
                },
            },
        },
    ]

    const options = {
        responsive: 'standard',
        fixedHeader: true,
        fixedSelectColumn: false,
        // filters: false,
        filter: false,
        // filterType: 'dropdown',
        download: false,
        print: false,
        jumpToPage: true,
        rowsPerPage: 5,
        rowsPerPageOptions: [5],
        selectableRows: 'none',

        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)
            }
        },
    }
    return (
        <>
            <SimpleCard>
                <div className="container">
                    <ThemeProvider theme={themeee}>
                        <MUIDataTable
                            title={
                                <Stack spacing={2} direction="row">
                                    <Typography variant="h6">
                                        User Guests
                                        {isLoading && (
                                            <CircularProgress
                                                size={24}
                                                style={{
                                                    marginLeft: 15,
                                                    position: 'relative',
                                                    top: 4,
                                                }}
                                            />
                                        )}
                                        <FormControl
                                            // variant="outlined"
                                            // fullWidth
                                            size="small"
                                            style={{
                                                width: 230,
                                                marginLeft: '1rem',
                                            }}
                                        >
                                            <InputLabel id="demo-simple-select-label">
                                                Filter by company
                                            </InputLabel>
                                            <Select
                                                key={filter}
                                                labelId="demo-simple-select-label"
                                                id="demo-simple-select-label"
                                                displayEmpty
                                                label="Filter by company"
                                                // defaultValue={filter}
                                                value={filter || 'all'}
                                                onChange={handleFilterChange}
                                            >
                                                <MenuItem value="all" key="all">
                                                    All
                                                </MenuItem>
                                                {companies.map((cp) => (
                                                    <MenuItem
                                                        value={cp._id}
                                                        key={cp._id}
                                                    >
                                                        {cp.name}
                                                    </MenuItem>
                                                ))}
                                            </Select>
                                        </FormControl>
                                    </Typography>
                                </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()
                                UserGuestsService.deleteRecord({ id: deleteId })
                                    .then((res) => {
                                        getData()
                                        console.log(
                                            'Successfullly deleted',
                                            res
                                        )
                                    })
                                    .catch((err) => {
                                        console.log('ERROR', err)
                                    })
                            }}
                            color="primary"
                        >
                            Confirm
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        </>
    )
}
export default UserGuests
