import { React, useEffect, useState } from 'react';

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

// project import
import Avatar from 'components/@extended/Avatar';
import MainCard from 'components/MainCard';

import axios from 'axios';

import AddressAutocomplete, { geocodeAddress } from 'components/nearle_components/AddressAutocomplete';
import Loader from 'components/Loader';
import { enqueueSnackbar } from 'notistack';
import { useNavigate } from 'react-router';
import CloseIcon from '@mui/icons-material/Close';
import TitleCard from '../titleCard';

const CreateCustomer = () => {
  const appId = localStorage.getItem('applocationid');
  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 [city, setCity] = useState('');
  const [zipcode, setZipcode] = useState('');
  const [address, setAddress] = useState('');
  const [suburb, setSuburb] = useState('');
  const [latlong, setLatlong] = useState({});
  const [firstname, setFirstname] = useState('');
  const [doorno, setDoorno] = useState('');
  const [landmark, setLandmark] = useState('');
  const [tenantinfo, setTenantinfo] = useState({});
  const [inputValue2, setInputValue2] = useState('');
  const [appLocaLat, setAppLocaLat] = useState();
  const [appLocaLng, setAppLocaLng] = useState();
  const [locaName, setLocoName] = useState('Select Location');
  const [locations, setLocations] = useState('Select Location');
  const [tenantlist, setTenantlist] = useState([]);
  const userid = localStorage.getItem('userid');
  const [isAppLocation, setIsAppLocation] = useState(false);
  const [tenantLocations, setTenantlocations] = useState([]);
  const [isClient, setisclient] = useState(false);
  const [tid, setTid] = useState(0);
  const [isBusiness, setIsBusiness] = useState(false);
  const [tenanatLocoId, setTenanatLocoId] = useState(localStorage.getItem('locationid'));
  const [tenantlocation, setTenantlocation] = useState('');
  const [isLocation, setIsLocation] = useState(false);
  const [pickCust, setPickCust] = useState({});
  const [startPoint, setStartPoint] = useState({ latitude: 0, longitude: 0 });

  const navigate = useNavigate();

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

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

  // ============================================= || Address Autocomplete (pick) || =============================================
  // `overwriteFields: false` is used by the manual-typing fallback below — it only
  // sets the map pin (lat/lng) and leaves the Address box / Door No / Area / City /
  // State / Postcode exactly as the operator typed them, instead of replacing that
  // text with the geocoder's own (often less specific) label for the resolved point.
  // A real dropdown pick (onPlaceSelected) still gets the full overwrite as before.
  const handlePickPlaceSelected = (place, { overwriteFields = true } = {}) => {
    const lat = place.geometry.location.lat();
    const lng = place.geometry.location.lng();
    setStartPoint({ latitude: lat, longitude: lng });
    if (!overwriteFields) {
      setPickCust((prev) => ({ ...prev, latitude: lat, longitude: lng }));
      return;
    }
    setInputValue2(`${place.name}, ${place.formatted_address}`);
    setAddress(`${place.name} ${place.formatted_address}`);
    setPickCust({ ...pickCust, address: `${place.name} ${place.formatted_address}` });
    const address = {
      address: `${place.name} ${place.formatted_address}`,
      street_number: '',
      route: '',
      locality: '',
      sublocality_level_1: '',
      administrative_area_level_3: '',
      administrative_area_level_1: '',
      country: '',
      postal_code: ''
    };
    place.address_components.forEach((component) => {
      component.types.forEach((type) => {
        switch (type) {
          case 'street_number':
            address.street_number = component.long_name;
            break;
          case 'route':
            address.route = component.long_name;
            break;
          case 'locality':
            address.locality = component.long_name;
            break;
          case 'sublocality_level_1':
            address.sublocality_level_1 = component.long_name;
            break;
          case 'administrative_area_level_3':
            address.administrative_area_level_3 = component.long_name;
            break;
          case 'administrative_area_level_1':
            address.administrative_area_level_1 = component.long_name;
            break;
          case 'country':
            address.country = component.long_name;
            break;
          case 'postal_code':
            address.postal_code = component.long_name;
            break;
          default:
            break;
        }
      });
    });

    setPickCust({
      ...pickCust,
      address: address.address,
      doorno: `${address.street_number} ${address.route}`,
      suburb: address.administrative_area_level_3,
      city: address.locality,
      state: address.administrative_area_level_1,
      postcode: address.postal_code,
      latitude: place.geometry.location.lat(),
      longitude: place.geometry.location.lng()
    });
  };
  // ============================================= || Fallback geocode for manually typed address || =============================================
  // AddressAutocomplete only resolves lat/lng when a suggestion is actually clicked
  // from its dropdown (handlePickPlaceSelected). The common real-world case is an
  // operator typing/pasting the full address into that single Address box and never
  // clicking a suggestion — that left startPoint at (0,0) forever, and because the
  // submit validation below used to check pickCust.latitude for an empty string
  // that's never actually set, customers were saved with latitude/longitude "0"/"0"
  // with no warning at all. This covers both the raw Address-box text and the
  // manually filled Location/City/Postcode fields as a fallback, reusing the same
  // handler a real dropdown selection would call so the rest of the fields fill in too.
  useEffect(() => {
    if (startPoint.latitude !== 0 || startPoint.longitude !== 0) return undefined;
    const manualFields = [doorno, pickCust.suburb, pickCust.city, pickCust.state, pickCust.postcode].filter(Boolean).join(', ');
    const manualAddress =
      (inputValue2 && inputValue2.trim().length >= 6 && inputValue2) || (pickCust.suburb && pickCust.city && manualFields);
    if (!manualAddress) return undefined;
    const timer = setTimeout(async () => {
      const place = await geocodeAddress(manualAddress, { bias: { lat: appLocaLat, lng: appLocaLng } });
      if (place) handlePickPlaceSelected(place, { overwriteFields: false });
    }, 800);
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [inputValue2, doorno, pickCust.suburb, pickCust.city, pickCust.state, pickCust.postcode, appLocaLat, appLocaLng]);

  // ==================================================== || getapplocations || ====================================================
  const getapplocations = async () => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/utils/getapplocations/?applocationid=${appId}`)
      .then((res) => {
        console.log('getapplocations', res);
        const { latitude, longitude } = res.data.details[0];
        if (res.data.status) {
          setAppLocaLat(latitude);
          setAppLocaLng(longitude);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };
  useEffect(() => {
    getapplocations();
  }, [appId]);

  // ==============================|| fetchAppLocations ||============================== //
  const fetchAppLocations = async () => {
    try {
      const locationRes = await axios.get(`${process.env.REACT_APP_URL}/partners/getlocations/?userid=${userid}`);
      // const updatedLocations = [
      //   ...locationRes.data.details,
      //   { partnername: 'All', applocationid: -1 }
      // ];
      // console.log('fetchAppLocations', updatedLocations);
      console.log('fetchAppLocations', locationRes.data.details);
      setLocations(locationRes.data.details);
    } catch (err) {
      console.log('locationRes', err);
    }
  };
  useEffect(() => {
    fetchAppLocations();
  }, []);

  // ===================================================== || fetchtenantinfolist || =====================================================

  const fetchtenantinfolist = async (id) => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/tenants/gettenants/?applocationid=${id}&status=active`)

      .then((res) => {
        console.log(res);
        if (res.data.status) {
          let arr = [];
          res.data.details.map((val) => {
            arr.push({
              ...val,
              label: `${val.tenantname}`
            });
          });
          setTenantlist(arr);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };
  // ============================================= || gettenantlocations (branches) || =============================================
  const gettenantlocations = async (id) => {
    try {
      const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantlocations/?tenantid=${id}`);
      console.log('gettenantlocations', res.data.details);
      if (res.data.details.length == 1) {
        setIsLocation(true);
        setTenantlocations(res.data.details);
        setTenanatLocoId(res.data.details[0].locationid);
        setTenantlocation(res.data.details[0].locationaddress); //client address
        setIsBusiness(true);
      } else {
        setTenantlocations(res.data.details);
        setIsBusiness(false); // became true after select from tenanatLocations
      }
    } catch (err) {
      console.log('gettenantlocations', err);
    }
  };

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

  const fetchtenantinfo = async (tid) => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/tenants/gettenantinfo/?tenantid=${tid}`)
      .then((res) => {
        console.log('fetchtenantinfo', res.data.details);
        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 createprofile = async () => {
    let obj = {
      applocationid: +appId,
      tenantid: +localStorage.getItem('tenantid'),
      customerid: 0,
      configid: 1,
      firstname: firstname,
      dialcode: '+91',
      contactno: mobilenumber,
      email: emailaddress,
      doorno: doorno,
      address: pickCust.address,
      suburb: pickCust.suburb,
      city: pickCust.city,
      state: pickCust.state,
      postcode: pickCust.postcode,
      landmark: landmark,
      latitude: startPoint.latitude.toString(),
      longitude: startPoint.longitude.toString(),
      profileimage: '',
      devicetype: '',
      deviceid: '',
      customertoken: '',
      primaryaddress: 1
    };
    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('/customers');
          } 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 />}
      <TitleCard
        title={'Create Customer'}
        secondary={
          <Button variant="contained" color="secondary" onClick={() => navigate('/nearle/customers')}>
            Back
          </Button>
        }
      />

      <MainCard>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <Grid container spacing={3}>
              {/* ===================================================== || Name|| ===================================================== */}
              <Grid item xs={12} sm={6}>
                <Stack spacing={1.25}>
                  <InputLabel htmlFor="personal-last-name">Name</InputLabel>
                  <TextField
                    fullWidth
                    id="personal-last-name"
                    placeholder="Name"
                    onChange={(e) => setFirstname(e.target.value)}
                    value={firstname}
                    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"
                      fullWidth
                      placeholder="Phone Number"
                      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>
              {/* ===================================================== || Email|| ===================================================== */}

              <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>
              {/* ===================================================== || door no || ===================================================== */}

              <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>

              {/* ===================================================== || Address || ===================================================== */}

              <Grid item xs={12}>
                <Stack spacing={1.25}>
                  <InputLabel htmlFor="personal-email"> Address</InputLabel>
                  <AddressAutocomplete
                    id="addressAuto1"
                    fullWidth
                    value={inputValue2}
                    onChange={setInputValue2}
                    onPlaceSelected={handlePickPlaceSelected}
                    bias={{ lat: appLocaLat, lng: appLocaLng }}
                    TextFieldProps={{
                      variant: 'outlined',
                      InputProps: {
                        endAdornment: (
                          <IconButton
                            onClick={() => {
                              setInputValue2('');
                              setPickCust({
                                ...pickCust,
                                doorno: '',
                                suburb: '',
                                city: '',
                                postcode: '',
                                landmark: ''
                              });
                              setStartPoint({ latitude: 0, longitude: 0 });
                            }}
                            size="small"
                          >
                            <CloseIcon />
                          </IconButton>
                        )
                      }
                    }}
                  />
                </Stack>
              </Grid>

              <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) => setPickCust({ ...pickCust, suburb: e.target.value })}
                    value={pickCust.suburb}
                    autoComplete="off"
                  />
                </Stack>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1.25}>
                  <InputLabel htmlFor="personal-zipcode">City</InputLabel>
                  <TextField
                    fullWidth
                    id="personal-zipcode"
                    placeholder="City"
                    onChange={(e) => setPickCust({ ...pickCust, city: e.target.value })}
                    value={pickCust.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) => setPickCust({ ...pickCust, state: e.target.value })}
                    value={pickCust.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) => setPickCust({ ...pickCust, postcode: e.target.value })}
                    value={pickCust.postcode}
                    autoComplete="off"
                  />
                </Stack>
              </Grid>

              <Grid item xs={12}>
                <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>
          </Grid>
          <Grid item xs={12}>
            <Stack direction="row" justifyContent="flex-end" alignItems="center" spacing={2}>
              <Button
                variant="contained"
                onClick={() => {
                  if (appId === '') {
                    opentoast('Select Applocation ');
                  } else if (tid === '') {
                    opentoast('Select Tenant');
                  } else if (firstname === '') {
                    opentoast('Enter Name');
                  } else if (mobilenumber === '') {
                    opentoast('Enter Mobile Number ');
                  } else if (address === '') {
                    opentoast('Enter Address ');
                  } else if (pickCust.city === '') {
                    opentoast('Enter City ');
                  } else if (pickCust.state === '') {
                    opentoast('Enter State ');
                  } else if (pickCust.suburb === '') {
                    opentoast('Enter location ');
                  } else if (pickCust.postcode === '') {
                    opentoast('Enter Post Code ');
                  } else if (landmark === '') {
                    opentoast('Enter Land Mark ');
                  } else if (!startPoint.latitude || !startPoint.longitude) {
                    opentoast('Could not locate address on map, please recheck the address');
                  } else {
                    createprofile();
                  }
                }}
              >
                Create
              </Button>
            </Stack>
          </Grid>
        </Grid>
      </MainCard>
    </>
  );
};

export default CreateCustomer;
