import { useEffect, useState } from 'react';

// material-ui
import { useTheme } from '@mui/material/styles';
import { Box, Button, FormLabel, Grid, InputLabel, MenuItem, Select, Stack, TextField, Typography } from '@mui/material';

// third-party
// import { PatternFormat } from 'react-number-format';

// 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 { useNavigate } from 'react-router';
// import { setLocationType } from 'react-geocode';

// const avatarImage = require.context('assets/images/users', true);

// styles & constant
// const ITEM_HEIGHT = 48;
// const ITEM_PADDING_TOP = 8;
// const MenuProps = {
//     PaperProps: {
//         style: {
//             maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP
//         }
//     }
// };

const Createrider = () => {
  const theme = useTheme();
  const [selectedImage, setSelectedImage] = useState(undefined);
  const [avatar, setAvatar] =
    useState();
    // avatarImage(`./default.png`)
  const [businessname, setBusinessname] = useState('');
  const [businessno, setBusinessno] = useState('');
  // const [role, setRole] = useState('');
  const [mobilenumber, setMobilenumber] = useState('');
  const [emailaddress, setEmailaddress] = useState('');
  const [city, setCity] = useState('');
  const [zipcode, setZipcode] = useState('');
  const [address, setAddress] = useState('');
  const [state, setState] = useState('');
  const [suburb, setSuburb] = useState('');
  const [latlong, setLatlong] = useState({});
  const [profiledetails, setProfiledetails] = useState({});
  const [primarycontact, setPrimarycontact] = useState('');
  const [firstname, setFirstname] = useState('');
  const [doorno, setDoorno] = useState('');
  const [landmark, setLandmark] = useState('');
  const [tenantinfo, setTenantinfo] = useState({});

  const navigate = useNavigate();

  Geocode.setApiKey(process.env.REACT_APP_GOOGLE_MAPS_API_KEY);
  // Geocode.setApiKey('AIzaSyCF4KatYCI3vqz1_H3kiHeyS3yCMfYToh8');

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

  useEffect(() => {
    //  fetchprofiledetails(localStorage.getItem('appuserid'));
    // fetchprofiledetails(181);
    if (localStorage.getItem('tenantid')) {
      fetchtenantinfo(localStorage.getItem('tenantid'));
    }
  }, []);

  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
    });
    // console.log(alertmessage)
  };

  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);
      });
  };

  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']
    }
  });

  const createprofile = async () => {
    console.log('res', businessname, businessno, mobilenumber, emailaddress, address, city, zipcode);

    // if (!businessname) {
    //     opentoast('Fill Business name')
    // } else if (!businessno) {
    //     opentoast('Fill Registration No')
    // }
    //  else
    if (!firstname) {
      opentoast('Fill Full name');
    } else if (!mobilenumber) {
      opentoast('Fill Mobile Number');
    } else if (!emailaddress) {
      opentoast('Fill emailaddress');
    } else if (!address) {
      opentoast('Fill Address');
    } else if (!city) {
      opentoast('Fill City');
    } else if (!zipcode) {
      opentoast('Fill post code');
    } else if (!suburb) {
      opentoast('Fill suburb');
    } else if (!emailaddress) {
      opentoast('Fill emailaddress');
    } else if (!latlong.lat || !latlong.lng) {
      opentoast('Choose valid address');
    } else {
      let obj = {
        customerid: 0,
        configid: 1,
        firstname: firstname,
        applocationid: tenantinfo.applolcationid,
        profileimage: '',
        dialcode: '+91',
        contactno: mobilenumber,
        devicetype: '',
        deviceid: '',
        customertoken: '',
        address: address,
        suburb: suburb,
        city: city,
        state: state,
        postcode: zipcode,
        landmark: landmark,
        doorno: doorno,
        latitude: latlong.lat.toString(),
        longitude: latlong.lng.toString(),
        tenantid: parseInt(localStorage.getItem('tenantid')),
        email: emailaddress
      };

      console.log(obj);

      setLoading(true);
      try {
        await axios
          .post(`${process.env.REACT_APP_URL}/customers/create`, obj)
          .then((res) => {
            console.log(res);
            if (res.data.status) {
              enqueueSnackbar(' Created Successfully ', {
                variant: 'success',
                anchorOrigin: { vertical: 'top', horizontal: 'right' },
                autoHideDuration: 2000
              });
              navigate('/clients');
              // setTimeout(()=>{
              //     fetchprofiledetails(localStorage.getItem('appuserid'));

              // },2000)
            } else if (res.data.message == 'Customer Already available') {
              enqueueSnackbar('Customer Already available', {
                variant: 'error',
                anchorOrigin: { vertical: 'top', horizontal: 'right' },
                autoHideDuration: 2000
              });
            }
            setLoading(false);
          })
          .catch((err) => {
            console.log(err);

            setLoading(false);
            enqueueSnackbar(err.message, {
              variant: 'error',
              anchorOrigin: { vertical: 'top', horizontal: 'right' },
              autoHideDuration: 2000
            });
          });
      } catch (err) {
        console.log(err);
        setLoading(false);
      }
    }
  };

  return (
    <>
      {loading && <Loader />}

      <Grid item xs={12} sx={{ mb: 2 }}>
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Typography variant="h3">Create Rider</Typography>
        </Stack>
      </Grid>
      <MainCard>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <MainCard
              // title="Contact Information"
              sx={{ height: '100%' }}
            >
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-last-name">Admin Name</InputLabel>
                    <TextField
                      fullWidth
                      id="personal-last-name"
                      placeholder="Name"
                      onChange={(e) => setFirstname(e.target.value)}
                      value={firstname}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                <Grid item xs={12} sm={6}></Grid>
                <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
                        // customInput={TextField}
                        placeholder="Phone Number"
                        // defaultValue="8654239581"
                        // onBlur={() => { }}
                        onChange={(e) => {
                          if (e.target.value.toString().length <= 10) {
                            setMobilenumber(e.target.value);
                          }
                        }}
                        value={mobilenumber}
                        autoComplete="off"
                        // disabled
                        sx={{ cursor: 'not-allowed' }}
                      />
                    </Stack>
                  </Stack>
                </Grid>
                <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) => setEmailaddress(e.target.value)}
                      value={emailaddress}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>

                <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)}
                      inputRef={materialRef}
                    />
                  </Stack>
                </Grid>

                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Suburb</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Location"
                      onChange={(e) => setSuburb(e.target.value)}
                      value={suburb}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                <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) => setCity(e.target.value)}
                      value={city}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>

                <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) => setState(e.target.value)}
                      value={state}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-zipcode">Post Code</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="956754"
                      type="number"
                      id="personal-zipcode"
                      placeholder="Zipcode"
                      onChange={(e) => setZipcode(e.target.value)}
                      value={zipcode}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>

                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-location">Door No</InputLabel>
                    <TextField
                      fullWidth
                      // defaultValue="New York"
                      id="personal-location"
                      placeholder="Door No"
                      onChange={(e) => setDoorno(e.target.value)}
                      value={doorno}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Stack spacing={1.25}>
                    <InputLabel htmlFor="personal-email">Landmark</InputLabel>
                    <TextField
                      type="email"
                      fullWidth
                      // defaultValue="stebin.ben@gmail.com"
                      id="personal-email"
                      placeholder="Landmark"
                      onChange={(e) => setLandmark(e.target.value)}
                      value={landmark}
                      autoComplete="off"
                    />
                  </Stack>
                </Grid>
              </Grid>
            </MainCard>
          </Grid>
          <Grid item xs={12}>
            <Stack direction="row" justifyContent="flex-end" alignItems="center" spacing={2}>
              <Button variant="contained" onClick={() => createprofile()}>
                Create
              </Button>
            </Stack>
          </Grid>
        </Grid>
      </MainCard>
    </>
  );
};

export default Createrider;
