import { useEffect, useState } from 'react';

// material-ui
import { useLocation, useNavigate } from 'react-router-dom';

import {
  Avatar,
  Box,
  Button,
  Grid,
  InputLabel,
  MenuItem,
  Select,
  Stack,
  TextField,
  Typography,
  Autocomplete,
  useMediaQuery,
  useTheme
} from '@mui/material';
import { MdDirectionsBike } from 'react-icons/md';
import { DT, tint } from 'themes/dt/tokens';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';

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

// project import
import MainCard from 'components/MainCard';
import { getMiler, updateMiler, getAdminTenant } from 'pages/api/doormileApi';
import { fetchAppLocations as fetchZoneLocations } from 'pages/api/api';
import AddressAutocomplete from 'components/nearle_components/AddressAutocomplete';
import Loader from 'components/Loader';
import { enqueueSnackbar } from 'notistack';
import dayjs from 'dayjs';
import CircularLoader from 'components/CircularLoader';

const EditRider = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const location = useLocation();
  const [riderdata, setRiderdata] = useState(null);
  const navigate = useNavigate();
  const [address, setAddress] = useState('');
  const [suburb, setSuburb] = useState('');
  const [city, setCity] = useState('');
  const [state, setState] = useState('');

  const [partner, setPartner] = useState({});
  const [vehiclelist, setVehiclelist] = useState([]);
  const [accountlist, setAccountlist] = useState([]);
  const [partnerlist, setPartnerlist] = useState([]);

  const [shiftlist, setShiftlist] = useState([]);
  const [locaName, setLocoName] = useState();

  const [loading, setLoading] = useState(false);

  const fetchRiderData = async (id) => {
    try {
      const miler = await getMiler(id);
      setRiderdata(miler);
      fetchridershifts(miler?.applocationid);
    } catch (error) {
      console.log('fetchmanagerList', error);
    }
  };
  useEffect(() => {
    // /admin/milers/:id routes key off milerprofileid, not userid (confirmed
    // live — GET /admin/milers/:userid 404s; userid on a miler row points at
    // the underlying app-user account, a different resource).
    fetchRiderData(location.state.riderdata.milerprofileid);
  }, []);

  useEffect(() => {
    console.log('riderdata', riderdata);
  }, [riderdata, address]);

  useEffect(() => {
    setAddress(location.state.riderdata.address);
    setSuburb(location.state.riderdata.suburb);
    setCity(location.state.riderdata.city);
    setState(location.state.riderdata.state);
  }, []);

  useEffect(() => {
    if (localStorage.getItem('tenantid')) {
      fetchtenantinfo(localStorage.getItem('tenantid'));
    }
    fetchvehicle();
    fetchaccounttype();
  }, []);

  useEffect(() => {
    if (partner.applocationid) {
      fetchridershifts(partner.applocationid);
    }
  }, [partner.applocationid]);

  const fetchtenantinfo = async (tid) => {
    setLoading(true);
    try {
      await getAdminTenant(tid);
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  // No vehicle-type/account-type lookup endpoint in the new API — these lists
  // stay empty (dropdowns render with no options) instead of crashing.
  const fetchvehicle = async () => setVehiclelist([]);

  const fetchaccounttype = async () => setAccountlist([]);

  // ==============================|| fetchAppLocations ||============================== //
  useEffect(() => {
    fetchZoneLocations().then(setPartnerlist);
  }, []);

  // No rider-shift lookup endpoint in the new API.
  const fetchridershifts = async () => setShiftlist([]);

  const handleAddressPlaceSelected = (place) => {
    setAddress(place.formatted_address);

    let city1, state1, 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':
            state1 = place.address_components[i].long_name;
            break;
          case 'sublocality':
          case 'sublocality_level_1':
            suburb1 = place.address_components[i].long_name;
            break;
        }
      }
    }
    setCity(city1 || '');
    setState(state1 || '');
    setSuburb(suburb1 || '');
  };

  const updateRider = async () => {
    setLoading(true);
    // PUT /admin/milers/:id has no documented fields for bank/vehicle/shift
    // details (the old ridersettings sub-object) — only the miler's own
    // identity/contact/tenant/zone fields carry over. Those settings stay in
    // local state but no longer persist server-side until the new API grows
    // matching endpoints.
    //
    // POST /admin/milers (the confirmed create body) has a single
    // `displayname` field — no firstname/lastname split exists on a miler at
    // all. This used to reconstruct displayname from riderdata.firstname/
    // lastname, which fetchRiderData never populates (the GET response has
    // no such fields either), so it always sent displayname: '' and silently
    // blanked the rider's name on every save.
    try {
      const res = await updateMiler(riderdata.milerprofileid, {
        contactno: riderdata.phone,
        displayname: riderdata.displayname,
        email: riderdata.email,
        tenantid: riderdata.tenantid,
        applocationid: riderdata.applocationid
      });
      if (res.success) {
        enqueueSnackbar(`Updated Sucessfully`, {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
        setRiderdata(null);
        navigate('/doormile/riders');
      } else {
        enqueueSnackbar(res.message || 'Update Failed', {
          variant: 'error',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
      }
    } catch (err) {
      enqueueSnackbar(err.message || 'Update Failed', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
    } finally {
      setLoading(false);
    }
  };
  return (
    <>
      {loading && (
        <>
          <Loader />
          <CircularLoader />
        </>
      )}
      <MainCard
        sx={{ borderRadius: DT.radiusCard + 'px', boxShadow: DT.shadowSoft, borderColor: DT.borderSubtle }}
        title={
          <Stack
            direction={{ xs: 'column', sm: 'row' }}
            justifyContent="space-between"
            alignItems={{ xs: 'stretch', sm: 'center' }}
            spacing={{ xs: 1.5, sm: 0 }}
            sx={{
              width: '100%',
              height: '100%',
              p: 2,
              background: `linear-gradient(135deg, ${tint('#C01227')} 0%, ${tint('#D25463')} 100%)`
            }}
          >
            <Stack direction="row" spacing={1.5} alignItems="center">
              <Avatar sx={{ width: 40, height: 40, bgcolor: DT.brand }}>
                <MdDirectionsBike size={20} />
              </Avatar>
              <Typography variant="h3">Edit Rider</Typography>
            </Stack>
            <Button
              startIcon={<ArrowBackIcon />}
              variant="outlined"
              fullWidth={isMobile}
              onClick={() => {
                setRiderdata(null);
                navigate('/doormile/riders');
              }}
            >
              Back to Riders
            </Button>
          </Stack>
        }
      >
        <Box
          sx={{
            maxHeight: 'calc(100vh - 280px)',
            overflowY: 'auto',
            overflowX: 'hidden',
            scrollbarGutter: 'stable',
            scrollBehavior: 'smooth'
          }}
        >
          <Stack display={'flex'} spacing={{ xs: 2.5, sm: 5 }}>
            {/* || =========================================== || Contact Information || =========================================== || */}
            <MainCard
              title={
                <Typography variant="h4" sx={{ m: 2 }}>
                  Contact Information
                </Typography>
              }
            >
              <Grid container spacing={{ xs: 2, sm: 3 }}>
                {/* ========================== || Display Name || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-display-name">Display Name</InputLabel>
                    <TextField
                      fullWidth
                      id="personal-display-name"
                      value={riderdata?.displayname || ''}
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          displayname: e.target.value
                        });
                      }}
                      placeholder="Name"
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||  Login Name || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-auth-name">Login Name</InputLabel>
                    <TextField fullWidth id="personal-auth-name" value={riderdata?.authname || ''} disabled autoComplete="off" />
                  </Stack>
                </Grid>
                {/* ========================== ||   Phone Number || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-phone">Phone Number</InputLabel>
                    <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                      <Select defaultValue="+1" disabled sx={{ cursor: 'not-allowed' }}>
                        <MenuItem value="+1">+91</MenuItem>
                      </Select>
                      <TextField
                        type="number"
                        id="personal-phone"
                        // format="##########"
                        // mask="_"
                        fullWidth
                        placeholder="Phone Number"
                        onChange={(e) => {
                          setRiderdata({
                            ...riderdata,
                            phone: e.target.value
                          });
                        }}
                        value={riderdata?.phone || ''}
                        autoComplete="off"
                        // disabled
                        sx={{ cursor: 'not-allowed' }}
                      />
                    </Stack>
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||  Email Address || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-email">Email Address</InputLabel>
                    <TextField
                      type="email"
                      fullWidth
                      // defaultValue="stebin.ben@gmail.com"
                      id="personal-email"
                      placeholder="Email Address"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          email: e.target.value
                        });
                      }}
                      value={riderdata?.email}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||Address || ==========================  */}
                <Grid item xs={12}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-address">Address</InputLabel>
                    <AddressAutocomplete
                      id="personal-address"
                      fullWidth
                      placeholder="Address"
                      value={address}
                      onChange={setAddress}
                      onPlaceSelected={handleAddressPlaceSelected}
                    />
                  </Stack>
                </Grid>
                {/* ========================== || Location|| ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Location</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Location"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          suburb: e.target.value
                        });
                        setSuburb(e.target.value);
                      }}
                      value={suburb}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== || City|| ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-zipcode">City</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="956754"
                      // type='number'
                      id="personal-zipcode"
                      placeholder="City"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          city: e.target.value
                        });
                        setCity(e.target.value);
                      }}
                      value={city}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== || State|| ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">State</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="State"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          state: e.target.value
                        });
                        setState(e.target.value);
                      }}
                      value={state}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||   Identification No|| ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Identification No</InputLabel>
                    <TextField
                      fullWidth
                      id="personal-location"
                      placeholder="Identification No"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          identificationno: e.target.value
                        });
                      }}
                      value={riderdata?.identificationno}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||  City / Zone || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">City / Zone</InputLabel>
                    <Autocomplete
                      disablePortal
                      id="combo-box-demo"
                      options={partnerlist}
                      getOptionLabel={(option) => `${option.locationname}`}
                      sx={{ width: { xs: '100%', sm: 300 }, height: '30px', ml: { xs: 0, sm: 3 }, zIndex: '100' }}
                      onChange={(event, value) => {
                        if (value) {
                          // This picker is fetchAppLocations() (hub-derived
                          // cities), not a Partners resource — the field used
                          // to write a `partnerid` that doesn't exist on
                          // these options (always undefined) alongside the
                          // real applocationid. Only applocationid is a
                          // confirmed miler field.
                          setLocoName(value.locationname);
                          fetchridershifts(value.applocationid);
                          setRiderdata({
                            ...riderdata,
                            applocationid: value.applocationid
                          });
                        } else {
                          setPartner({});
                        }
                      }}
                      renderInput={(params) => <TextField {...params} label={locaName || riderdata?.city} />}
                    />
                    {/* <Autocomplete
                      renderInput={(params) => <TextField {...params} label={locaName} />}
                      label={locaName}
                      options={partnerlist}
                      getOptionLabel={(option) => `${option.locationname}`}
                      onChange={(e, val) => {
                        if (val) {
                          setPartner(val);
                          setRiderdata({
                            ...riderdata,
                            partnerid: val.partnerid
                          });
                        } else {
                          setPartner({});
                        }
                      }}
                      freeSolo
                    /> */}
                  </Stack>
                </Grid>
              </Grid>
            </MainCard>
            {/* || =========================================== || Charges || =========================================== || */}

            <MainCard
              title={
                <Typography variant="h4" sx={{ m: 2 }}>
                  Charges
                </Typography>
              }
            >
              <Grid container spacing={{ xs: 2, sm: 3 }}>
                {/* ========================== ||  Shift Type || ==========================  */}

                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Shift Type</InputLabel>

                    <Autocomplete
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label={riderdata?.starttime && riderdata?.endtime ? `${riderdata?.starttime} - ${riderdata?.endtime}` : 'Choose'}
                        />
                      )}
                      // disabled
                      options={shiftlist}
                      onChange={(e, val) => {
                        if (val) {
                          console.log('shift', val);
                          setRiderdata({
                            ...riderdata,
                            shiftid: val.shiftid,
                            additionalkm: val.additionalkm,
                            additionalcharges: val.additionalcharges,
                            basefare: val.basefare,
                            starttime: val.starttime,
                            endtime: val.endtime
                          });
                        }
                      }}
                      freeSolo
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||  Base Fare || ==========================  */}

                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Base Fare</InputLabel>
                    <TextField
                      fullWidth
                      id="personal-location"
                      placeholder="Base Fare"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          basefare: e.target.value
                        });
                      }}
                      value={riderdata?.basefare}
                      autoComplete="off"
                      disabled
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||  Additional Kms || ==========================  */}

                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Additional Kms</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Additional Kms"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          additionalkm: e.target.value
                        });
                      }}
                      value={riderdata?.additionalkm}
                      autoComplete="off"
                      disabled
                    />
                  </Stack>
                </Grid>
                {/* ========================== || Other Charges || ==========================  */}

                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Other Charges</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Other Charges"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          additionalcharges: e.target.value
                        });
                      }}
                      value={riderdata?.additionalcharges}
                      autoComplete="off"
                      disabled
                    />
                  </Stack>
                </Grid>
              </Grid>
            </MainCard>

            {/* || =========================================== || Bank Details || =========================================== || */}

            <MainCard
              title={
                <Typography variant="h4" sx={{ m: 2 }}>
                  Bank Details
                </Typography>
              }
            >
              <Grid container spacing={{ xs: 2, sm: 3 }}>
                {' '}
                {/* ========================== || Account No|| ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Account No</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Account No"
                      value={riderdata?.accountno}
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          accountno: e.target.value
                        });
                      }}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||  Account Name || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Account Name</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Account Name"
                      value={riderdata?.accountname}
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          accountname: e.target.value
                        });
                      }}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||  Account Type || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Account Type</InputLabel>

                    <Autocomplete
                      renderInput={(params) => (
                        <TextField {...params} label={riderdata?.accounttype == '' ? 'Choose' : riderdata?.accounttype} />
                      )}
                      // disabled
                      options={accountlist}
                      // value={clientdetail}
                      onChange={(e, val) => {
                        console.log('ac type', val);
                        if (val) {
                          setRiderdata({
                            ...riderdata,
                            accounttype: val.label
                          });
                          // fetchroles(val.tenantid);
                        }
                      }}
                      freeSolo
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||   Bank Name|| ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Bank Name</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Bank Name"
                      value={riderdata?.bankname}
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          bankname: e.target.value
                        });
                      }}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||  IFSC Code || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">IFSC Code</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="IFSC Code"
                      value={riderdata?.ifsccode}
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          ifsccode: e.target.value
                        });
                      }}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||  Branch || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Branch</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Branch"
                      value={riderdata?.branch}
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          branch: e.target.value
                        });
                      }}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
              </Grid>
            </MainCard>

            {/* || =========================================== || Vehicle Details || =========================================== || */}

            <MainCard
              title={
                <Typography variant="h4" sx={{ m: 2 }}>
                  Vehicle Details
                </Typography>
              }
            >
              <Grid container spacing={{ xs: 2, sm: 3 }}>
                {/* ========================== ||  Vehicle Name || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Vehicle Name</InputLabel>
                    <Autocomplete
                      renderInput={(params) => (
                        <TextField {...params} label={riderdata?.vehiclename == '' ? 'Choose' : riderdata?.vehiclename} />
                      )}
                      // disabled
                      options={vehiclelist}
                      // value={clientdetail}
                      onChange={(e, val) => {
                        if (val) {
                          console.log('vehi', val);
                          setRiderdata({
                            ...riderdata,
                            vehiclename: val.label,
                            vehicleid: val.apptypeid
                          });

                          // fetchroles(val.tenantid);
                        }
                      }}
                      freeSolo
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||  Vehicle No || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Vehicle No</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Vehicle No"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          vehicleno: e.target.value
                        });
                      }}
                      value={riderdata?.vehicleno}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||  Model Year || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Model Year</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Model Year"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          model: e.target.value
                        });
                      }}
                      value={riderdata?.model}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== || Vehicle Color || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Vehicle Color</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Vehicle Color"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          color: e.target.value
                        });
                      }}
                      value={riderdata?.color}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||   License No || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">License No</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="License No"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          licenseno: e.target.value
                        });
                      }}
                      value={riderdata?.licenseno}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== ||  Insurance No || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Insurance No</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Insurance No"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          insuranceno: e.target.value
                        });
                      }}
                      value={riderdata?.insuranceno}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>{' '}
                {/* ========================== || Insurance Expiry Date  || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Insurance Expiry Date</InputLabel>
                    <LocalizationProvider
                      dateAdapter={AdapterDayjs}
                      //  sx={{ width: '100%' }}
                    >
                      <DatePicker
                        label="Date"
                        value={dayjs(riderdata?.insurancedate)}
                        onChange={(e) => {
                          setRiderdata({
                            ...riderdata,
                            insurancedate: dayjs(e.$d).format('YYYY-MM-DD 00:00:00')
                          });
                        }}
                        sx={{ width: '100%' }}
                        // disablePast
                        // minDate={dayjs().add(1, 'day')}
                      />
                    </LocalizationProvider>
                  </Stack>
                </Grid>
              </Grid>
            </MainCard>
          </Stack>
          {/* ================= FIXED BOTTOM ACTION ================= */}
        </Box>
      </MainCard>
      {/* ========================== ||  Update || ==========================  */}
      <Box
        sx={{
          position: 'sticky',
          bottom: 0,
          backgroundColor: DT.surfaceAlt,
          p: 2,
          zIndex: 10,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          borderTop: 'none'
        }}
      >
        <Stack direction={{ xs: 'column-reverse', sm: 'row' }} justifyContent="flex-end" spacing={2}>
          <Button startIcon={<ArrowBackIcon />} variant="outlined" fullWidth={isMobile} onClick={() => navigate('/doormile/riders')}>
            Back to Riders
          </Button>
          <Button
            variant="contained"
            fullWidth={isMobile}
            onClick={() => {
              updateRider();
            }}
          >
            Update
          </Button>
        </Stack>
      </Box>
    </>
  );
};

export default EditRider;
