import React, { useState, useEffect } from 'react'
import {
    CircularProgress,
    Typography,
    FormControlLabel,
    Switch,
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
    Button,
    Stack,
} from '@mui/material'
import MUIDataTable from 'mui-datatables'
import { chunk } from 'lodash'
import useAuth from 'app/hooks/useAuth'
import { useNavigate, useLocation } 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 OrderService from 'app/services/allThingsLocals/OrderService'
import OrderStatus from './OrderStatus'

function Customers(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 handleClose = () => {
        setDeleteId('')
        setOpenDialogue(false)
    }

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

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

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

    const getData = () => {
        setIsLoading(true)
        OrderService.ordersQuery({ search: '', page: 0, 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) => {
            OrderService.ordersQuery({ 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 columns = [
        {
            name: 'Order #',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <>
                            <Button
                                size="small"
                                variant="contained"
                                onClick={(e) =>
                                    navigate(
                                        '/admin/order-detail/' +
                                            data[tableMeta.rowIndex]._id,
                                        {
                                            state: {
                                                data: data[tableMeta.rowIndex],
                                                prevPath: location.pathname,
                                            },
                                        }
                                    )
                                }
                            >
                                {data[tableMeta.rowIndex]._id &&
                                    data[tableMeta.rowIndex]._id.slice(-6)}
                            </Button>
                        </>
                    )
                },
            },
        },

        {
            name: 'status',
            label: 'Status',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    let status = data[tableMeta.rowIndex].status
                    return (
                        <div>
                            <OrderStatus status={status} />
                        </div>
                    )
                },
            },
        },
        {
            name: 'paymentMethod',
            label: 'Payment Method',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    let paymentMethod = data[tableMeta.rowIndex].paymentStatus
                    return (
                        <div>
                            {paymentMethod == 'cash' ? (
                                <p>Cash</p>
                            ) : (
                                <p>Card</p>
                            )}
                        </div>
                    )
                },
            },
        },
        {
            name: 'paymentStatus',
            label: 'Payment Status',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    let payment = data[tableMeta.rowIndex].paymentStatus
                    return <div>{payment ? <p>Paid</p> : <p>Not Paid</p>}</div>
                },
            },
        },
        {
            name: 'amount',
            label: 'Total Price',
            options: {
                // filter: true,
                sort: true,
            },
        },
        {
            name: 'Seller',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <>
                            {data[tableMeta.rowIndex].seller &&
                                data[tableMeta.rowIndex].seller.fullName}
                        </>
                    )
                },
            },
        },
        {
            name: 'Customer',
            options: {
                sort: true,
                customBodyRender: (value, tableMeta, updateValue) => {
                    return (
                        <>
                            {data[tableMeta.rowIndex].customer &&
                                data[tableMeta.rowIndex].customer.name}
                        </>
                    )
                },
            },
        },
        // {
        //     name: 'role',
        //     label: 'Role',
        //     options: {
        //         // filter: true,
        //         sort: true,
        //     },
        // },

        // {
        //     name: 'Icon',
        //     options: {
        //         sort: true,
        //         customBodyRender: (value, tableMeta, updateValue) => {
        //             return (
        //                 <a target="_blank" href={data[tableMeta.rowIndex].icon}>
        //                     <VisibilityIcon />
        //                 </a>
        //             )
        //         },
        //     },
        // },
        // {
        //     name: 'Actions',
        //     options: {
        //         sort: true,
        //         customBodyRender: (value, tableMeta, updateValue) => {
        //             return (
        //                 <>
        //                     <Link
        //                         to={`/admin/fleet-types/edit/${
        //                             data[tableMeta.rowIndex]._id
        //                         }`}
        //                         title="Edit Fleet Type"
        //                     >
        //                         <EditIcon />
        //                     </Link>

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

    const options = {
        responsive: 'simple',
        // filters: false,
        filter: false,
        // filterType: 'dropdown',

        jumpToPage: true,
        rowsPerPage: 5,
        rowsPerPageOptions: [5],

        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 (
        <>
            <div className="container">
                <MUIDataTable
                    title={
                        <Stack spacing={2} direction="row">
                            <Typography variant="h6">
                                Customers
                                {isLoading && (
                                    <CircularProgress
                                        size={24}
                                        style={{
                                            marginLeft: 15,
                                            position: 'relative',
                                            top: 4,
                                        }}
                                    />
                                )}
                            </Typography>
                            {/*
                            <Button
                                variant="contained"
                                onClick={() =>
                                    navigate('/admin/fleet-types/add')
                                }
                            >
                                Add Fleet Type
                            </Button> */}
                        </Stack>
                    }
                    data={data}
                    columns={columns}
                    options={options}
                />
            </div>
            <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()
                                OrderService.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 Customers
