import { useEffect, useState } from "react";

// material-ui
import { useTheme } from "@mui/material/styles";
import { useLocation, useNavigate } from "react-router-dom";

import {
  Box,
  Button,
  FormLabel,
  Grid,
  InputLabel,
  MenuItem,
  Select,
  Stack,
  TextField,
  Typography,
  Autocomplete,
} from "@mui/material";

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 Avatar from "components/@extended/Avatar";
import MainCard from "components/MainCard";
import {
  // facebookColor, linkedInColor, twitterColor
  ThemeMode,
} from "config";
import axios from "axios";
// assets
import {
  // FacebookFilled, LinkedinFilled, TwitterSquareFilled,
  CameraOutlined,
} from "@ant-design/icons";
import { usePlacesWidget } from "react-google-autocomplete";
import Loader from "components/Loader";
import Geocode from "react-geocode";
import { enqueueSnackbar } from "notistack";
import dayjs from "dayjs";

const EditRider = () => {
  const [riderdata, setRiderdata] = useState({});
  const location = useLocation();
  const navigate = useNavigate();
  const theme = useTheme();
  const [selectedImage, setSelectedImage] = useState(undefined);
  const [avatar, setAvatar] = useState();

  const [businessname, setBusinessname] = useState("");
  const [businessno, setBusinessno] = useState("");

  const [mobilenumber, setMobilenumber] = useState("");
  const [emailaddress, setEmailaddress] = useState("");

  const [zipcode, setZipcode] = useState("");
  const [address, setAddress] = useState("");
  const [suburb, setSuburb] = useState("");
  const [city, setCity] = useState("");
  const [state, setState] = useState("");

  const [latlong, setLatlong] = useState({});
  const [profiledetails, setProfiledetails] = useState({});
  const [primarycontact, setPrimarycontact] = useState("");
  const [firstname, setFirstname] = useState("");
  const [lastname, setLastname] = useState("");

  const [doorno, setDoorno] = useState("");
  const [landmark, setLandmark] = useState("");
  const [tenantinfo, setTenantinfo] = useState({});

  const [idno, setIdno] = useState("");
  const [basefare, setBasefare] = useState("");
  const [additionalkms, setAdditionalkms] = useState("");
  const [othercharges, setOthercharges] = useState("");

  const [account, setAccount] = useState({});
  const [accountType, setAccountType] = useState("");

  const [accountname, setAccountname] = useState("");
  const [accountno, setAccountno] = useState("");
  const [bankname, setBankname] = useState("");
  const [ifsc, setIfsc] = useState("");
  const [branch, setBranch] = useState("");

  const [vehicle, setVehicle] = useState({});
  const [vehicleno, setVehicleno] = useState("");
  const [Modelyear, setModelyear] = useState("");
  const [vehiclecolor, setVehiclecolor] = useState("");
  const [licenseno, setLicenseno] = useState("");
  const [insuranceno, setInsuranceno] = useState("");
  const [expirydate, setExpirydate] = useState("");

  const [partner, setPartner] = useState({});

  const [vehiclelist, setVehiclelist] = useState([]);
  const [accountlist, setAccountlist] = useState([]);
  const [partnerlist, setPartnerlist] = useState([]);

  const [shiftlist, setShiftlist] = useState([]);
  const [shift, setShift] = useState({});
  const [appId, setAppId] = useState(localStorage.getItem("ne-appId"));
  const [isShift, setIsShift] = useState(true);

  Geocode.setApiKey(process.env.REACT_APP_GOOGLE_MAPS_API_KEY);

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

  const fetchRiderData = async (id) => {
    try {
      let riderdataresponse = await axios.get(
        `https://jupiter.nearle.app/live/api/v1/partners/getriderdetail/?userid=${id}`
      );
      console.log("riderdataresponse", riderdataresponse.data.details);
      setRiderdata(riderdataresponse.data.details);
    } catch (error) {
      console.log("fetchmanagerList", error);
    }
  };

  useEffect(() => {
    fetchRiderData(location.state.riderdata.userid);
  }, []);

  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();
    fetchpartnerlist();
  }, []);

  // useEffect(() => {
  //   try {
  //     Geocode.fromAddress(address).then(
  //       (response) => {
  //         if (response.status == "OK") {
  //           const { lat, lng } = response.results[0].geometry.location;
  //           setLatlong({
  //             lat,
  //             lng,
  //           });
  //           console.log(response);
  //         }
  //       },
  //       (error) => {
  //         console.log(error);
  //       }
  //     );
  //   } catch (err) {
  //     console.log(err);
  //   }
  // }, [address]);

  const opentoast = (message) => {
    enqueueSnackbar(message, {
      variant: "error",
      anchorOrigin: { vertical: "top", horizontal: "right" },
      autoHideDuration: 2000,
    });
  };

  const fetchprofiledetails = async (userid) => {
    if (userid) {
      setLoading(true);
      try {
        await axios
          .get(`${process.env.REACT_APP_URL2}/tenants/getclient?id=${userid}`)
          .then((res) => {
            console.log(res);
            if (res.data.message === "Successful") {
              let res1 = res.data.details;
              setProfiledetails(res1);
              setBusinessname(res1.tenantname);
              setBusinessno(res1.registrationno);
              setMobilenumber(res1.contactno);
              setPrimarycontact(res1.primarycontact);
              setEmailaddress(res1.primaryemail);
              setAddress(res1.address);
              setCity(res1.city);
              setZipcode(res1.postcode);
              setState(res1.state);
              setSuburb(res1.suburb);
              setLatlong({
                lat: res1.latitude,
                lng: res1.longitude,
              });
            }
            setLoading(false);
          })
          .catch((err) => {
            console.log(err);
            setLoading(false);
          });
      } catch (err) {
        console.log(err);
        setLoading(false);
      }
    }
  };

  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 fetchvehicle = async (tid) => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/utils/getapptypes?tag=vehicle`)
      .then((res) => {
        console.log("fetchvehicle", res);
        let arr = [];
        res.data.map((val) => {
          arr.push({
            ...val,
            label: val.typename,
          });
        });
        setVehiclelist([...arr]);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };

  const fetchaccounttype = async () => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/utils/getapptypes?tag=accounttype`)
      .then((res) => {
        console.log(res);
        // if (res.data.status) {
        let arr = [];
        res.data.map((val) => {
          arr.push({
            ...val,
            label: val.typename,
          });
        });
        setAccountlist([...arr]);
        console.log(arr);
        // }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };

  const fetchpartnerlist = async () => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/partners/getpartners`)
      .then((res) => {
        console.log("fetchpartnerlist", res);
        // if (res.data.status) {
        let arr = [];
        res.data.details.map((val) => {
          arr.push({
            ...val,
            label: val.partnername,
          });
        });
        setPartnerlist([...arr]);
        console.log(arr);
        // }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };

  const fetchridershifts = async (pid) => {
    setLoading(true);
    await axios
      .get(
        `${process.env.REACT_APP_URL}/partners/getridershifts/?applocationid=${appId}`
      )
      .then((res) => {
        console.log("fetchridershifts", res);
        // if (res.data.status) {
        let arr = [];
        res.data.details.map((val) => {
          arr.push({
            ...val,
            label: val.shiftname,
          });
        });
        setShiftlist([...arr]);
        console.log(arr);
        // }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };
  useEffect(() => {
    fetchridershifts();
  }, [appId]);
  useEffect(() => {
    if (selectedImage) {
      setAvatar(URL.createObjectURL(selectedImage));
    }
  }, [selectedImage]);

  const { ref: materialRef } = usePlacesWidget({
    apiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
    onPlaceSelected: (place) => {
      console.log(place);
      setAddress(place.formatted_address);

      let city1, zipcode1, 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 "postal_code":
              zipcode1 = place.address_components[i].long_name;
              break;
            case "sublocality":
              suburb1 = place.address_components[i].long_name;
              break;
          }
        }
      }
      setCity(city1 || "");

      setState(state1 || "");
      setZipcode(zipcode1 || "");
      setSuburb(suburb1 || "");

      // setAddress(place.formatted_address)
    },
    // inputAutocompleteValue: "country",
    options: {
      // componentRestrictions: 'us',
      // types: ["establishment"]
      types: ["address" || "geocode"],
    },
  });
  useEffect(() => {
    console.log("address", address);
    console.log("suburb", suburb);
    console.log("city", city);
    console.log("state", state);
  }, [address, suburb, city, state]);

  const updateRider = async () => {
    // e.preventDefault();

    console.log("updated riderData", riderdata);
    await axios
      .put(`https://jupiter.nearle.app/live/api/v1/partners/updaterider`, {
        userid: riderdata.userid,
        contactno: riderdata.contactno,
        firstname: riderdata.firstname,
        lastname: riderdata.lastname,
        email: riderdata.email,
        address: riderdata.address,
        suburb: riderdata.suburb,
        city: riderdata.city,
        state: riderdata.state,
        partnerid: riderdata.partnerid,
        applocationid: riderdata.applocationid,
        ridersettings: {
          riderid: riderdata.riderid,
          userid: riderdata.userid,
          partnerid: riderdata.partnerid,
          shiftid: riderdata.shiftid,
          identificationno: riderdata.identificationno,
          basefare: riderdata.basefare,
          additionalkm: riderdata.additionalkm,
          othercharges: riderdata.othercharges,
          accountno: riderdata.accountno,
          accountname: riderdata.accountname,
          accounttypeid: riderdata.accounttypeid,
          accounttype: riderdata.accounttype,
          bankname: riderdata.bankname,
          ifsccode: riderdata.ifsccode,
          Branch: riderdata.branch,
          vehicleid: riderdata.vehicleid,
          vehiclename: riderdata.vehiclename,
          vehicleno: riderdata.vehicleno,
          model: riderdata.model,
          color: riderdata.color,
          licenseno: riderdata.licenseno,
          insurancedate: dayjs(riderdata.insurancedate).format(
            "YYYY-MM-DD HH:mm:ss"
          ),
        },
      })
      .then((response) => {
        console.log("post  response", response);
        if (response.status == 200) {
          enqueueSnackbar(`Updated Sucessfully`, {
            variant: "success",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        } else {
          enqueueSnackbar("Update Failed", {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        }
      });
  };
  return (
    <>
      {loading && <Loader />}

      <Grid item xs={12} sx={{ mb: 2 }}>
        <Stack
          direction="row"
          justifyContent="space-between"
          alignItems="center"
        >
          <Typography variant="h3">Edit Rider </Typography>
        </Stack>
      </Grid>
      <MainCard>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            {/* || =========================================== || Contact Information || =========================================== || */}
            <MainCard title="Contact Information" sx={{ height: "100%" }}>
              <Grid container spacing={3}>
                {/* ========================== || First Name || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-last-name">
                      First Name
                    </InputLabel>
                    <TextField
                      fullWidth
                      id="personal-last-name"
                      value={riderdata.firstname}
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          firstname: e.target.value,
                        });
                      }}
                      placeholder="Name"
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||  Last Name || ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-last-name">
                      Last Name
                    </InputLabel>
                    <TextField
                      fullWidth
                      id="personal-last-name"
                      placeholder="Name"
                      onChange={(e) => {
                        setRiderdata({
                          ...riderdata,
                          lastname: e.target.value,
                        });
                      }}
                      value={riderdata.lastname}
                      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,
                            contactno: e.target.value,
                          });
                        }}
                        value={riderdata.contactno}
                        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>
                    <TextField
                      fullWidth
                      // defaultValue="Street 110-B Kalians Bag, Dewan, M.P. New York"
                      id="personal-address"
                      placeholder="Address"
                      value={address}
                      onChange={(e) => {
                        setAddress(e.target.value);
                        setRiderdata({
                          ...riderdata,
                          address: e.target.value,
                        });
                      }}
                      inputRef={materialRef}
                    />
                  </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>
              </Grid>
            </MainCard>
          </Grid>
          {/* || =========================================== || Charges || =========================================== || */}
          <Grid
            item
            xs={12}
            //  sm={8}
          >
            <MainCard title="Charges">
              <Grid container spacing={3}>
                {/* ========================== ||  Choose Partner|| ==========================  */}
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">
                      Choose Partner
                    </InputLabel>

                    <Autocomplete
                      renderInput={(params) => (
                        <TextField {...params} label="Choose Partner" />
                      )}
                      options={partnerlist}
                      onChange={(e, val, reason) => {
                        setIsShift(false);
                        if (reason == "clear") {
                          setIsShift(false);
                        }
                        if (val) {
                          setPartner(val);
                          console.log("val", val);
                          setRiderdata({
                            ...riderdata,
                            partnerid: val.partnerid,
                          });

                          setAppId(val.applocationid);
                        } else {
                          setPartner({});
                        }
                      }}
                      freeSolo
                    />
                  </Stack>
                </Grid>
                {/* ========================== ||  Shift Type || ==========================  */}

                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">
                      Shift Type
                    </InputLabel>
                    <Autocomplete
                      value={
                        isShift
                          ? `${riderdata.starttime} - ${riderdata.endtime}`
                          : "Choose Shift"
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label={
                            isShift
                              ? `${riderdata.starttime} - ${riderdata.endtime}`
                              : "Choose Shift"
                          }
                        />
                      )}
                      options={shiftlist}
                      onChange={(e, val) => {
                        if (val) {
                          console.log("shift", val);
                          setIsShift(true);
                          setRiderdata({
                            ...riderdata,
                            shiftid: val.shiftid,
                            additionalkm: val.additionalkm,
                            additionalcharges: val.additionalcharges,
                            basefare: val.basefare,
                            starttime: val.starttime,
                            endtime: val.endtime,
                          });

                          setBasefare(val.basefare);
                          setAdditionalkms(val.additionalkm);
                          setOthercharges(val.additionalcharges);
                          setShift(val);
                        } else {
                          setBasefare("");
                          setAdditionalkms("");
                          setOthercharges("");
                          setShift({});
                        }
                      }}
                      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,
                        });
                        setBasefare(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,
                        });
                        setAdditionalkms(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,
                        });
                        setOthercharges(e.target.value);
                      }}
                      value={riderdata.additionalcharges}
                      autoComplete="off"
                      disabled
                    />
                  </Stack>
                </Grid>
              </Grid>
            </MainCard>
          </Grid>
          {/* || =========================================== || Bank Details || =========================================== || */}
          <Grid
            item
            xs={12}
            //  sm={8}
          >
            <MainCard title="Bank Details">
              <Grid container spacing={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,
                        });
                        setAccountno(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,
                        });
                        setAccountname(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,
                          });
                          setAccount(val);
                          setAccountType(val.label);
                          // fetchroles(val.tenantid);
                        } else {
                          setAccount({});
                        }
                      }}
                      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,
                        });
                        setBankname(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,
                        });
                        setIfsc(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,
                        });
                        setBranch(e.target.value);
                      }}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
              </Grid>
            </MainCard>
          </Grid>{" "}
          {/* || =========================================== || Vehicle Details || =========================================== || */}
          <Grid
            item
            xs={12}
            //  sm={8}
          >
            <MainCard title="Vehicle Details">
              <Grid container spacing={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);
                          setVehicle(val);
                          setRiderdata({
                            ...riderdata,
                            vehiclename: val.label,
                            vehicleid: val.apptypeid,
                          });

                          // fetchroles(val.tenantid);
                        } else {
                          setVehicle({});
                        }
                      }}
                      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,
                        });
                        setModelyear(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,
                        });
                        setVehiclecolor(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) => {
                          setExpirydate(
                            dayjs(e.$d).format("YYYY-MM-DD 00:00:00")
                          );
                          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>
          </Grid>
          {/* ========================== ||  Update || ==========================  */}
          <Grid item xs={12}>
            <Stack
              direction="row"
              justifyContent="flex-end"
              alignItems="center"
              spacing={2}
            >
              <Button
                variant="contained"
                onClick={() => {
                  updateRider();
                  setTimeout(() => {
                    navigate("/riders");
                  }, 1000);
                }}
              >
                Update
              </Button>
            </Stack>
          </Grid>
        </Grid>
      </MainCard>
    </>
  );
};

export default EditRider;
