import {
    FormControl,
    InputAdornment,
    Grid,
    Typography,
    Stack,
    Box,
    // Autocomplete,
    Button,
    // Stepper,
    // Step,
    // StepLabel,
    TextField,
    Autocomplete,
    CardActions,
    // CardActions,
    Chip,
    // AvatarGroup,
    //   RadioGroup,
    //   Radio
    Avatar,
    // List,
    // ListItem,
    // IconButton,
    // ListItemAvatar,
    // ListItemText,
    // Menu,
    // MenuItem,
    // ListItemIcon,
    // Link,
    Divider,
    Table,
    TableContainer,
    TableRow,
    TableCell,
    TableHead,
    TableBody,
    // FormLabel,
    Tooltip,
    DialogTitle,
    DialogContent,
    Checkbox,
    DialogActions,
    CircularProgress,
    ButtonGroup,
    FormLabel
    // LinkOutlined
} from '@mui/material';
import { useNavigate } from 'react-router';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';

import { PopupTransition } from 'components/@extended/Transitions';
// var utc = require('dayjs/plugin/utc')

import axios from 'axios';
import { useTheme } from '@mui/material/styles';
// import { usePlacesWidget } from "react-google-autocomplete";
import Geocode from "react-geocode";
// import {setApi} from "react-geocode";
import Autocomplete1 from "react-google-autocomplete";
// import logo from 'assets/images/location.png'
import Loader from 'components/Loader'

import {
    // EditOutlined,
    PlusOutlined,
    SearchOutlined
} from '@ant-design/icons';

import { DeleteOutlined } from '@ant-design/icons';

import MainCard from 'components/MainCard';
import {
    EnvironmentOutlined,
    // LinkOutlined, 
    // MailOutlined,
    // MoreOutlined,
    // PhoneOutlined
} from '@ant-design/icons';
import CheckCircleRoundedIcon from '@mui/icons-material/CheckCircleRounded';
// import VisibilityIcon from '@mui/icons-material/Visibility';
// import AccessTimeFilledIcon from '@mui/icons-material/AccessTimeFilled';
// import EditCalendarIcon from '@mui/icons-material/EditCalendar';
import AccessibilityNewIcon from '@mui/icons-material/AccessibilityNew';

// import { PatternFormat } from 'react-number-format';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { TimePicker } from '@mui/x-date-pickers/TimePicker';

// import DialogTitle from '@mui/material/DialogTitle';
import Dialog from '@mui/material/Dialog';
import {
    useEffect, useState, Fragment
    //  useReducer 
} from 'react';
// import { Label } from '@mui/icons-material';
import dayjs from 'dayjs';
// import { useDispatch } from 'react-redux';
// import { openSnackbar, closeSnackbar } from 'store/reducers/snackbar';
// import {Autocompletemap} from 'pages/autocompletemap'
import { enqueueSnackbar } from 'notistack';
// import { CheckBox } from '@mui/icons-material';
// dayjs.extend(utc)




const Createorder = () => {

    Geocode.setApiKey(process.env.REACT_APP_GOOGLE_MAPS_API_KEY)



    const navigate = useNavigate();
    const [open, setOpen] = useState({});
    const [open1, setOpen1] = useState('')
    const [open2, setOpen2] = useState(false)
    const [shift, setShift] = useState(1);
    const [clientlist, setClientlist] = useState([])
    const [clientdetail, setClientdetail] = useState([]);
    const [eventname, setEventname] = useState('');

    const [startdate, setStartdate] = useState(dayjs().format('MM-DD-YYYY'));
    const [enddate, setEnddate] = useState(dayjs().add(1, 'day').format('MM-DD-YYYY'));






    const [roleoptions, setRoleoptions] = useState([]);

    const theme = useTheme();

    const [otherinstructions, setOtherinstructions] = useState('');

    const [attireslist, setAttireslist] = useState([]);
    const [serviceaddonslist, setServiceaddonslist] = useState([]);
    const [orderaddonobj, setOrderaddonobj] = useState([]);

    const [stafflist, setStafflist] = useState([]);
    const [loading2, setLoading2] = useState(false);
    const [loading, setLoading] = useState(false)


    const [shiftarr, setShiftarr] = useState([]);
    const [shiftarr1, setShiftarr1] = useState([]);

    const [orderarr, setOrderarr] = useState([]);


    const [alertmessage, setAlertmessage] = useState('');
    const [tabstatus, setTabstatus] = useState('')
    const [tenantinfo, setTenantinfo] = useState({});
    const [searchword, setSearchword] = useState('');
    const [clientdetailarr, setClientdetailarr] = useState([])


    useEffect(() => {
        if (localStorage.getItem('tenantid')) {
            setOrderarr([{
                sno: 1,
                address: '',
                "customerid": '',
                "deliverytime": dayjs(),
                "deliverylocationid": '',
                "clientname": '',
                "contactno": '',
                "latitude": '',
                "longitude": ''
            }])
            // console.log(dayjs())
        }
    }, [])

    useEffect(() => {
        if (searchword) {
            //  setClientdetailarr()
            let arr = clientdetail.filter((val) => {

                return (val.address.toLowerCase().includes(searchword.toLowerCase())
                    || val.firstname.toLowerCase().includes(searchword.toLowerCase())
                    || val.contactno.toLowerCase().includes(searchword.toLowerCase())
                    //   || val.pickupaddress.toString().toLowerCase().includes(searchword.toLowerCase())
                    //   || val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase())

                )
            })
            console.log(arr)
            setClientdetailarr([...arr])
        } else {
            setClientdetailarr([...clientdetail])

        }

    }, [searchword])

    const fetchtenantinfo = async (tid) => {
        setLoading(true)
        await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantinfo/?tenantid=${tid}`)
            .then((res) => {
                console.log(res)
                if (res.data.status) {
                    setTenantinfo(res.data.details);
                }
                setLoading(false)
            }).catch((err) => {
                console.log(err)
                setLoading(false)
            })
    }

    const opentoast = (message) => {

        enqueueSnackbar(message, {
            variant: 'error', anchorOrigin: { vertical: 'top', horizontal: 'right' },
            autoHideDuration: 2000
        })
        console.log(alertmessage)


    }

    function closeAddressModal() {
        setOpen2(false);
    }



    const createsubmitobj1 = async () => {
        let arr = []
        let timecheck = false;
        let addresscheck = false;
        orderarr.map((val) => {
            if (!val.address) {
                addresscheck = true;
            }

            if (!val.deliverytime) {
                timecheck = true;
            }

            arr.push({
                "orderheaderid": 0,
                "tenantid": parseInt(localStorage.getItem('tenantid')),
                "locationid": tenantinfo.locationid,
                "moduleid": tenantinfo.moduleid,
                "configid": 7,
                "orderid": "",
                "customerid": val.customerid,
                "orderdate": dayjs().format('YYYY-MM-DD HH:mm:ss'),
                "orderstatus": "created",
                "pending": "",
                "processing": "",
                "ready": "",
                "delivered": "",
                "cancellled": "",
                "promoid": 0,
                "promoname": "",
                "promoterms": "",
                "promovalue": 0,
                "promoamount": 0,
                "orderamount": 0,
                "taxamount": 0,
                "ordercharges": 0,
                "ordervalue": 0,
                "itemcount": 1,
                "paymenttype": 64,
                "paymentstatus": 0,
                "deliverycharge": 0,
                "deliverytime": `${dayjs(startdate).format('YYYY-MM-DD')} ${dayjs(val.deliverytime.$d).format('HH:mm:ss')}`,
                "deliverylocationid": val.deliverylocationid,
                "deliveryaddress": val.address,
                "pickupaddress": tenantinfo.address,
                "pickuplat": tenantinfo.latitude,
                "pickuplong": tenantinfo.longitude,
                "ordernotes": otherinstructions,
                "remarks": "",
                "tenantuserid": parseInt(localStorage.getItem('tenantid')),
                "categoryid": tenantinfo.categoryid,
                "subcategoryid": tenantinfo.subcategoryid,
                "partnerid": tenantinfo.partnerid,
                "deliverylat":val.latitude,
                "deliverylong":val.longitude,
                "applocationid":parseInt(localStorage.getItem('applocationid'))

            })

        })

        if (timecheck) {
            opentoast('Choose Schedule Time')
        } else if (addresscheck) {
            opentoast('Choose Client')

        } else {
            setLoading(true)
            await axios.post(`${process.env.REACT_APP_URL}/orders/createorders`, arr)
                .then((res) => {
                    if (res.data.status) {
                        enqueueSnackbar('Order Created Successfully', {
                            variant: 'success', anchorOrigin: { vertical: 'top', horizontal: 'right' },
                            autoHideDuration: 2000
                        })
                        navigate('/orders')
                    } else {
                        opentoast(res.data.message)
                    }
                    setLoading(false)
                    console.log(res)

                }).catch((err) => {
                    console.log(err)
                    opentoast(err.data.message)
                    setLoading(false)

                })
            // opentoast('success')
        }

        console.log(arr)
    }




    useEffect(() => {
        if (localStorage.getItem('tenantid')) {
            // clientdetails(localStorage.getItem('tenantid'));
            fetchtenantinfo(localStorage.getItem('tenantid'))
        }

        // fetchattires();
        // fetchserviceaddons();
        // let arr = [];
        // arr.push({
        //     sno: arr.length + 1,
        //     address: "",
        //     starttime: "",
        //     endtime: "",
        //     latitude: '',
        //     longitude: '',
        //     state: "",
        //     city: "",
        //     orderattires: [],
        //     details: [{
        //         sno: 1,
        //         role: '',
        //         position: '',
        //         uniform: '',
        //         cost: 0,

        //         "orderdetailid": 0,
        //         "orderheaderid": 0,
        //         "tenantid": '',
        //         "locationid": 0,
        //         "productid": 1,
        //         "productname": "",
        //         "productdescription": "description1",
        //         "starttime": '',
        //         "endtime": '',
        //         "unpaidbreak": 0,
        //         "orderqty": 0,
        //         "price": 0,
        //         "unitid": 1,
        //         "unitname": "",
        //         "landingamount": 0,
        //         "taxamount": 0,
        //         "productsumprice": 0,
        //         "workhours": ''
        //     }],
        //     "clientstaff": []

        // })
        // setShiftarr1(arr)
        // setShiftarr([])
    }, [clientdetail.tenantname])








    useEffect(() => {
        console.log('shiftarr')
        console.log(shiftarr)

    }, [shiftarr])

    const clicked1 = (e) => {
        setShift(e);
    }

    const dialogopen = (i, result) => {
        console.log(i, result)
        setOpen({ shiftsno: result.sno, sno: i.sno })
    }
    const dialogclose = () => {

        setOpen('')
    }




    const clientdetails = async (tid) => {
        //     setClientdetail([{
        //         "address": 'ttt uuu vvvv',
        //         "customerid":10,
        //         "deliverylocationid": 20,
        //         "contactno":4444,
        //         "firstname":'test1',
        //     },
        //     {
        //         "address": '2ttt uuu vvvv',
        //         "customerid":11,
        //         "deliverylocationid": 21,
        //         "contactno":5555,
        //         "firstname":'test2',
        //     },
        //     {
        //         "address": '3ttt uuu vvvv',
        //         "customerid":12,
        //         "deliverylocationid": 22,
        //         "contactno":6666,
        //         "firstname":'test3',
        //     }
        // ])
        setLoading2(true)
        try {

            await axios.get(`${process.env.REACT_APP_URL}/customers/getbytid/?tenantid=${tid}`)

                .then((res) => {
                    if (res.data.status) {

                        setClientdetail(res.data.details)
                        if (!searchword) {
                            setClientdetailarr(res.data.details)
                        }

                    }
                    setLoading2(false)


                }).catch((err) => {
                    console.log(err)
                    setLoading2(false)
                    opentoast('server error')
                })

        } catch (err) {
            console.log(err);
            setLoading2(false)
            // opentoast('Something went wrong')

        }
    }






    return <>
        {(loading) &&

            <Loader />

        }
        <Grid container rowSpacing={4.5} columnSpacing={2.75}>

            <CardActions
                sx={{
                    position: 'sticky',
                    top: '60px',
                    bgcolor: theme.palette.background.default,
                    zIndex: 1000,
                    width: '100%'
                }}
            >
                <Grid item xs={12}
                >
                    <Stack direction={{ md: 'row', xs: 'column' }} sx={{ p: 1, ml: 1 }} justifyContent="space-between" alignItems="center" width="100%">
                        <Typography variant="h3">Create Order</Typography>
                    </Stack>
                </Grid>
            </CardActions>

            <Grid item xs={12} height='100%' sx={{ mt: -2 }}>
                <Box
                    sx={{ overflow: 'auto', border: 1, borderColor: 'grey.200', borderRadius: 2, backgroundColor: '#fff', p: 3 }}
                >
                    <ButtonGroup variant="outlined" >
                        <Button variant={(tabstatus == 0) ? 'contained' : 'outlined'} onClick={() => {
                            setTabstatus(0)
                            setOrderarr([{
                                sno: 1,
                                address: '',
                                "customerid": '',
                                "deliverytime": dayjs(),
                                "deliverylocationid": '',
                                "clientname": '',
                                "contactno": '',
                                "latitude": '',
                                "longitude": ''
                            }])
                        }}>Single</Button>
                        <Button variant={(tabstatus == 1) ? 'contained' : 'outlined'} onClick={() => {
                            setTabstatus(1)
                            setOrderarr([{
                                sno: 1,
                                address: '',
                                "customerid": '',
                                "deliverytime": dayjs(),
                                "deliverylocationid": '',
                                "clientname": '',
                                "contactno": '',
                                "latitude": '',
                                "longitude": ''
                            }])
                        }}>Multiple</Button>
                    </ButtonGroup>
                    <Grid container spacing={1}>







                        <Grid item xs={12}>
                            <MainCard sx={{ mt: 2 }}>
                                <Grid container spacing={1}>
                                    {/*<Grid item xs={12}>
                                        <Typography variant="h4">Event</Typography>
                                    </Grid>

                                    <Grid item md={6} xs={12}>


                                        <Stack direction={'column'} sx={{ height: '100%' }}>
                                            <TextField
                                                margin="normal"
                                                fullWidth
                                                id="eventname1"
                                                label="Event Name"
                                                variant="outlined"
                                                autoComplete='off'
                                                required
                                                value={eventname}
                                                onChange={(e) => {
                                                    if (clientdetail.tenantname) {


                                                        if (e.target.value.length <= 50) {
                                                            setEventname(e.target.value);
                                                        }
                                                    } else {
                                                        setAlertmessage('choose client');
                                                        opentoast('choose client');
                                                    }
                                                }}
                                                sx={{ m: 0 }}
                                            />

                                            <Typography variant="body2" align="right">{`${eventname.length}/50`}</Typography>
                                        </Stack>
                                    </Grid> */}
                                    <Grid item xs={12} md={8} sx={{ height: '100%' }} >
                                        <FormLabel>Pickup Location</FormLabel>

                                        <Box sx={{ border: '1px solid #bdbdbd', p: 1, borderRadius: 1 }}>

                                            <Typography color="secondary" sx={{ mr: 1 }}><EnvironmentOutlined />{' '}{tenantinfo.address || ''}
                                                {/* {'123, Tamil Kudimagan Nagar Rd, Vadakkuppattu, Kulattur, Chennai, Tamil Nadu 600117, India'} */}
                                            </Typography>

                                        </Box>
                                    </Grid>
                                    <Grid item xs={12} md={4} sx={{ height: '100%' }}>

                                        <LocalizationProvider dateAdapter={AdapterDayjs} sx={{ width: '100%' }}>
                                            <FormLabel>Date</FormLabel>
                                            <DatePicker

                                                // label='Date'
                                                format="DD-MM-YYYY"
                                                onChange={(e) => {
                                                    let dateres11 = dayjs().diff(dayjs(`${dayjs(e).format('YYYY-MM-DD')}`), 'd');
                                                    console.log('dateres11')
                                                    console.log(dateres11)
                                                    if (dateres11 <= 0) {
                                                        setStartdate(e);
                                                        setEnddate(e);

                                                    } else {
                                                        setAlertmessage('choose Upcoming Date');
                                                        opentoast('choose Upcoming Date')
                                                        setStartdate(NaN)
                                                    }

                                                }}
                                                value={dayjs(startdate)}
                                                sx={{ width: '100%' }}
                                                disablePast
                                            // minDate={dayjs().add(1, 'day')}

                                            />
                                        </LocalizationProvider>

                                    </Grid>


                                </Grid>
                            </MainCard>

                        </Grid>





                        {/* {shiftarr1.map((result) => {

                            return <> */}




                        <Grid item xs={12}>
                            <MainCard sx={{ height: '100%' }}>


                                <Stack direction={'row'} justifyContent={'space-between'} alignItems={'center'} sx={{ p: 1 }}>

                                    {/* <Typography variant="h4">Shift {result.sno}</Typography> */}

                                    <Stack direction={'row'} spacing={2}>

                                        {/* <Button
                                                    sx={{ minWidth: '10px !important' }}

                                                    color="warning" onClick={() => deleteshiftarr1({ sno: result.sno })}><DeleteOutlined /></Button> */}
                                    </Stack>
                                </Stack>

                                <Grid container spacing={2} sx={{ mb: 2 }}>

                                    {/* <Grid item xs={12} md={6}>

                                                <Autocomplete1
                                                    className='automap'
                                                    apiKey={process.env.REACT_APP_GOOGLE_MAPS_API_KEY}
                                                    style={{
                                                        width: "100%", height: '40px', borderRadius: '5px',
                                                        border: '1px solid #e0e0e0', textIndent: '10px', outline: 'none',
                                                        paddingLeft: '30px',
                                                        backgroundSize: '14px'
                                                    }}
                                                    onPlaceSelected={(place) => {
                                                        let city1, state, zipcode1, suburb1;
                                                        for (let i = 0; i < place.address_components.length; i++) {
                                                            for (let j = 0; j < place.address_components[i].types.length; j++) {
                                                                switch (place.address_components[i].types[j]) {
                                                                    case "locality":
                                                                        city1 = place.address_components[i].long_name;
                                                                        break;
                                                                    case "administrative_area_level_1":
                                                                        state = place.address_components[i].long_name;
                                                                        break;
                                                                    case "postal_code":
                                                                        zipcode1 = place.address_components[i].long_name;
                                                                        break;
                                                                    case "sublocality":
                                                                        suburb1 = place.address_components[i].long_name;
                                                                        break;
                                                                }
                                                            }
                                                        }
                                                        console.log(city1, state, zipcode1, suburb1)
                                                        let arr = shiftarr1;
                                                        try {
                                                            Geocode.fromAddress(place.formatted_address).then(
                                                                (response) => {
                                                                    const { lat, lng } = response.results[0].geometry.location;
                                                                    arr[result.sno - 1].latitude = lat;
                                                                    arr[result.sno - 1].longitude = lng;

                                                                    console.log(lat, lng);
                                                                },
                                                                (error) => {
                                                                    console.error(error);
                                                                }
                                                            );
                                                        } catch (err) {
                                                            console.log(err)
                                                        }
                                                        arr[result.sno - 1].city = city1 || '';
                                                        arr[result.sno - 1].state = state || '';

                                                        arr[result.sno - 1].address = place.formatted_address;
                                                        setShiftarr1([...arr]);

                                                    }}
                                                    options={{

                                                        types: ['address' || 'geocode']

                                                    }}
                                                    placeholder='Shift Location'

                                                    onChange={() => {
                                                        if (!eventname) {
                                                            setAlertmessage('Fill Event name');
                                                            opentoast('Fill Event name');
                                                        }
                                                    }}

                                                />

                                            </Grid> */}
                                    <Grid item xs={12}
                                        // md={6}
                                        sx={{ width: '100%' }}>

                                        <Grid container justifyContent={'right'} spacing={2} alignItems={'center'}>
                                            {/* 
                                                    <Grid item>

                                                        <Stack direction={'row'} spacing={1} alignItems={'center'}>
                                                            {result.clientstaff.map((val11) => {

                                                                return <>
                                                                    <Tooltip title={val11.firstname}>
                                                                        <Avatar sx={{ bgcolor: '#2196f3', width: 30, height: 30 }} alt="A"  >{val11.firstname.charAt(0).toUpperCase()}</Avatar>
                                                                    </Tooltip>
                                                                </>
                                                            })

                                                            }
                                                        </Stack>

                                                    </Grid> */}
                                            <Grid item>
                                                <Button variant="outlined" onClick={() => {
                                                    // if (clientdetail.tenantid) {
                                                    //     fetchtenantstaffs(clientdetail.tenantid)

                                                    //     setOpen1(result.sno)
                                                    // } else {
                                                    //     opentoast('choose client')
                                                    // }
                                                    if (localStorage.getItem('tenantid')) {
                                                        clientdetails(localStorage.getItem('tenantid'));
                                                        // fetchtenantinfo(localStorage.getItem('tenantid'))
                                                    }
                                                    setOpen2(true)

                                                }} color="success" startIcon={<PlusOutlined />}>ADD Clients</Button>
                                            </Grid>
                                        </Grid>





                                        <Dialog
                                            // maxWidth="sm"
                                            // minWidth='md'
                                            open={open2}
                                            onClose={closeAddressModal}
                                            sx={{ '& .MuiDialog-paper': { p: 0 }, '& .MuiBackdrop-root': { opacity: '0.5 !important' } }}
                                        >
                                            <DialogTitle>
                                                <Stack direction="row" justifyContent="space-between" alignItems="center">
                                                    <Typography variant="h5">Select Address</Typography>
                                                    {/* <Button startIcon={<PlusOutlined />} onClick={closeAddressModal} color="primary">
            Add New
          </Button> */}
                                                </Stack>
                                            </DialogTitle>
                                            <Divider />
                                            <DialogContent sx={{ p: 2.5 }}>
                                                {(loading2) ?

                                                    <>
                                                        <Stack direction={'row'} width={'100%'} justifyContent={'center'}>
                                                            <CircularProgress />
                                                        </Stack>
                                                    </>
                                                    :
                                                    <>


                                                        <FormControl sx={{ width: '100%', pb: 2 }}>
                                                            <TextField
                                                                autoFocus
                                                                id="name"
                                                                InputProps={{
                                                                    startAdornment: (
                                                                        <InputAdornment position="start">
                                                                            <SearchOutlined />
                                                                        </InputAdornment>
                                                                    )
                                                                }}
                                                                placeholder="Search"
                                                                fullWidth
                                                                onChange={(e) => {
                                                                    setSearchword(e.target.value)
                                                                }}

                                                            />
                                                        </FormControl>
                                                        <Stack spacing={2}>
                                                            {/* <Address handlerAddress={handlerAddress} /> */}

                                                            {clientdetailarr.map((address) => (
                                                                <Box
                                                                    // onClick={() => handlerAddress(address)}
                                                                    onClick={() => {
                                                                        if (tabstatus == 1) {
                                                                            if (orderarr[0].address == '') {
                                                                                setOrderarr([{
                                                                                    sno: 1,
                                                                                    address: address.address,
                                                                                    "customerid": address.customerid,
                                                                                    "deliverytime": dayjs(),
                                                                                    "deliverylocationid": address.deliverylocationid,
                                                                                    "clientname": address.firstname,
                                                                                    "contactno": address.contactno,
                                                                                    "latitude": address.latitude,
                                                                                    "longitude": address.longitude
                                                                                }])
                                                                            } else {
                                                                                if (orderarr.find((val2) => val2.customerid == address.customerid)) {
                                                                                    if (orderarr.length > 1) {
                                                                                        let arr = orderarr;
                                                                                        let res = orderarr.find((val2) => val2.customerid == address.customerid)
                                                                                        arr.splice(res.sno - 1, 1);
                                                                                        let arr1 = []
                                                                                        arr.map((val2, k) => {
                                                                                            arr1.push({
                                                                                                sno: k + 1,
                                                                                                'address': val2.address,
                                                                                                "customerid": val2.customerid,
                                                                                                "deliverytime": val2.deliverytime,
                                                                                                "deliverylocationid": val2.deliverylocationid,
                                                                                                "clientname": val2.clientname,
                                                                                                "contactno": val2.contactno,
                                                                                                "latitude": val2.latitude,
                                                                                                "longitude": val2.longitude
                                                                                            })
                                                                                        })
                                                                                        setOrderarr([...arr1])
                                                                                    } else {
                                                                                        setOrderarr([{
                                                                                            sno: 1,
                                                                                            address: '',
                                                                                            "customerid": '',
                                                                                            "deliverytime": dayjs(),
                                                                                            "deliverylocationid": '',
                                                                                            "clientname": '',
                                                                                            "contactno": '',
                                                                                            "latitude": '',
                                                                                            "longitude": ''
                                                                                        }])
                                                                                    }
                                                                                } else {
                                                                                    console.log(clientdetail)
                                                                                    let arr = orderarr;
                                                                                    arr.push({
                                                                                        sno: arr.length + 1,
                                                                                        'address': address.address,
                                                                                        "customerid": address.customerid,
                                                                                        "deliverytime": dayjs(),
                                                                                        "deliverylocationid": address.deliverylocationid,
                                                                                        "clientname": address.firstname,
                                                                                        "contactno": address.contactno,
                                                                                        "latitude": address.latitude,
                                                                                        "longitude": address.longitude
                                                                                    })
                                                                                    setOrderarr([...arr])
                                                                                }

                                                                            }

                                                                        }

                                                                        if (tabstatus == 0) {
                                                                            setOrderarr([{
                                                                                sno: 1,
                                                                                address: address.address,
                                                                                "customerid": address.customerid,
                                                                                "deliverytime": dayjs(),
                                                                                "deliverylocationid": address.deliverylocationid,
                                                                                "clientname": address.firstname,
                                                                                "contactno": address.contactno,
                                                                                "latitude": address.latitude,
                                                                                "longitude": address.longitude
                                                                            }])

                                                                            // console.log({
                                                                            //     sno: 1,
                                                                            //     address: address.address,
                                                                            //     "customerid": address.customerid,
                                                                            //     "deliverytime": "",
                                                                            //     "deliverylocationid": address.deliverylocationid,
                                                                            // })
                                                                        }

                                                                    }}
                                                                    key={address.contactno}
                                                                    sx={{
                                                                        width: '100%',
                                                                        border: '1px solid',
                                                                        borderColor: 'grey.200',
                                                                        borderRadius: 1,
                                                                        cursor: 'pointer',
                                                                        p: 1.25,
                                                                        '&:hover': {
                                                                            // bgcolor: theme.palette.primary.lighter,
                                                                            // borderColor: theme.palette.primary.lighter
                                                                            bgcolor: (orderarr.find((val2) => val2.customerid == address.customerid)) ? '#e1bee7' : ''
                                                                        },
                                                                        bgcolor: (orderarr.find((val2) => val2.customerid == address.customerid)) ? '#e1bee7' : ''
                                                                    }}
                                                                >
                                                                    <Stack direction={'row'} justifyContent={'space-between'}>
                                                                        <Typography textAlign="left" variant="subtitle1">
                                                                            {address.firstname}
                                                                        </Typography>
                                                                        {(orderarr.find((val2) => val2.address == address.address)) &&
                                                                            <CheckCircleIcon color='primary' />
                                                                        }

                                                                    </Stack>
                                                                    <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
                                                                        <Typography textAlign="left" variant="body2" color="secondary">
                                                                            {address.address}
                                                                        </Typography>
                                                                        <Typography textAlign="left" variant="body2" color="secondary">
                                                                            {address.contactno}
                                                                        </Typography>
                                                                        <Typography textAlign="left" variant="body2" color="secondary">
                                                                            {/* {address.email} */}
                                                                        </Typography>
                                                                    </Stack>
                                                                </Box>
                                                            ))}



                                                        </Stack>
                                                    </>
                                                }
                                            </DialogContent>
                                            <Divider />
                                            <DialogActions sx={{ p: 2.5, minWidth: '300px' }}>
                                                <Button variant='contained' color="error"
                                                    onClick={() => {
                                                        closeAddressModal()
                                                    }}
                                                >
                                                    Cancel
                                                </Button>
                                                <Button
                                                    onClick={closeAddressModal}
                                                    color="primary" variant="contained">
                                                    OK
                                                </Button>
                                            </DialogActions>
                                        </Dialog>
                                    </Grid>

                                </Grid>


                                <TableContainer sx={{ width: '100%', borderBottom: 1, borderColor: 'divider' }}>
                                    <Table
                                        sx={{ width: '100%' }}
                                    >
                                        <TableHead>
                                            <TableRow>
                                                <TableCell>#</TableCell>
                                                {/* <TableCell sx={{ minWidth: '170px' }}>Role</TableCell> */}
                                                <TableCell>Client</TableCell>
                                                <TableCell>Schedule Time</TableCell>
                                                {/* <TableCell>End Time</TableCell> */}
                                                {/* <TableCell>Pickup Location</TableCell> */}
                                                {/* <TableCell>Break</TableCell> */}
                                                <TableCell>Drop Location</TableCell>
                                                {/* <TableCell align='center'>Value</TableCell> */}
                                                <TableCell align='center'>Action</TableCell>

                                            </TableRow>
                                        </TableHead>
                                        <TableBody>

                                            {orderarr.map((val) => {
                                                return <>


                                                    <TableRow key={val.sno} >
                                                        <TableCell>{val.sno}</TableCell>
                                                        <TableCell>
                                                            <Stack direction="row" alignItems="center" spacing={1} justifyContent="flex-start">
                                                                <Avatar
                                                                    alt=""
                                                                    size="sm"
                                                                    //   src={row.profileimage}
                                                                    sx={{
                                                                        width: '25px',
                                                                        height: '25px'
                                                                    }}
                                                                >

                                                                </Avatar>
                                                                <Stack direction="column">
                                                                    <Typography variant="caption">{val.clientname}</Typography>
                                                                    <Typography variant="caption" color="textSecondary">


                                                                        {val.contactno}
                                                                    </Typography>
                                                                </Stack>
                                                            </Stack>
                                                        </TableCell>

                                                        <TableCell>
                                                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                                                                <TimePicker
                                                                    label="Schedule Time"
                                                                    timeSteps={{ minutes: 15 }}
                                                                    onChange={(e) => {
                                                                        console.log(e)
                                                                        if (e.$d) {


                                                                            let arr = orderarr;
                                                                            arr[val.sno - 1].deliverytime = e
                                                                            setOrderarr([...arr])
                                                                            console.log(arr)
                                                                        }
                                                                        // let arr = shiftarr1;
                                                                        // let dateres11 = dayjs().diff(dayjs(`${dayjs(startdate).format('YYYY-MM-DD')} ${dayjs(e).format('HH:mm:ss')}`), 'm');
                                                                        // console.log('dateres11')
                                                                        // console.log(dateres11)
                                                                        // if (dateres11 < 0) {


                                                                        //     arr[result.sno - 1].details[val.sno - 1].starttime = dayjs(e.$d);

                                                                        //     arr[result.sno - 1].details[val.sno - 1].endtime = dayjs(dayjs(e.$d).add(4, 'hours').$d);


                                                                        // }








                                                                    }
                                                                    }

                                                                    sx={{ width: '150px' }}
                                                                    value={val.deliverytime || null}


                                                                />
                                                            </LocalizationProvider>

                                                        </TableCell>
                                                        <TableCell>{val.address}</TableCell>


                                                        {/* <TableCell>
                                                                        {(val.cost) &&
                                                                            <>
                                                                                {`${val.cost}/hr`}
                                                                            </>
                                                                        }

                                                                    </TableCell> */}


                                                        {/* <TableCell align='center'>{(val.role && val.position) &&
                                                                        <>
                                                                            {val.landingamount}
                                                                        </>
                                                                    }
                                                                        {(!val.position || !val.role) &&
                                                                            0
                                                                        }
                                                                    </TableCell> */}

                                                        <TableCell>

                                                            <Stack direction={'row'} justifyContent={'center'}>
                                                                <Button sx={{ minWidth: '10px !important' }} color="error" onClick={() => {
                                                                    let arr = orderarr;
                                                                    if (orderarr.length > 1) {
                                                                        arr.splice(val.sno - 1, 1);
                                                                        let arr1 = []
                                                                        arr.map((val2, k) => {
                                                                            arr1.push({
                                                                                sno: k + 1,
                                                                                'address': val2.address,
                                                                                "customerid": val2.customerid,
                                                                                "deliverytime": val2.deliverytime,
                                                                                "deliverylocationid": val2.deliverylocationid,
                                                                            })
                                                                        })
                                                                        setOrderarr([...arr1])
                                                                    } else {
                                                                        setOrderarr([{
                                                                            sno: 1,
                                                                            address: '',
                                                                            "customerid": '',
                                                                            "deliverytime": '',
                                                                            "deliverylocationid": '',
                                                                        }])
                                                                    }

                                                                    // arr[val.sno-1]
                                                                }}><DeleteOutlined /></Button>
                                                            </Stack>

                                                        </TableCell>





                                                    </TableRow>
                                                </>
                                            })

                                            }

                                        </TableBody>
                                    </Table>
                                </TableContainer>
                                {/* <Grid item xs={12}>
                                            <Button
                                                color="primary"
                                                endIcon={<PlusOutlined />}

                                                onClick={() => addarr(result)}

                                                sx={{ m: 2 }}
                                                variant="dashed"
                                           
                                            >

                                                ADD
                                            </Button>
                                        </Grid> */}
                            </MainCard>





                        </Grid>


                        {/* </>
                        }) */}

                        {/* } */}
                        {/* <Grid item xs={12}>
                            <Button
                                color="error"
                                endIcon={<PlusOutlined />}

                                onClick={addshiftarr1}

                                variant="dashed"



                            >

                                ADD SHIFTS
                            </Button>
                        </Grid> */}
                        <Grid item xs={12}>

                            <Grid container spacing={1}>

                                <Grid item xs={12}>
                                    <MainCard title='Notes' sx={{ height: '100%' }}>

                                        <TextField id="outlined-multiline-static" sx={{ width: '100%', height: '100%' }} multiline rows={4} placeholder='Notes'
                                            value={otherinstructions} onChange={(e) => setOtherinstructions(e.target.value)} />

                                    </MainCard>
                                </Grid>
                            </Grid>




                        </Grid>






                    </Grid >

                    <Stack direction='row' justifyContent='flex-end' sx={{ mt: 2, backgroundColor: '#fff' }} >
                        <Button variant='contained' onClick={() => {

                            createsubmitobj1()

                        }}>Create</Button>


                    </Stack>
                </Box >
            </Grid >
            <Grid item xs={12} >




            </Grid>

        </Grid >
    </>
}

export default Createorder;