"use client";

import { useEffect, useRef, useState } from "react";
import { Modal } from "@/components/ui/modal";
import {
  GoogleMap,
  LoadScript,
  Autocomplete,
  Marker,
} from "@react-google-maps/api";
import { Button } from "../ui/button";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import apis from "@/utils/apis";
import { useGlobalContext } from "@/context/Provider";

const libraries: any = ["places"];
const CheckoutAddress = ({
  title,
  isOpen,
  setIsOpen,
  defaultCenter,
}: any) => {
  const autocompleteRef = useRef<any>(null);
  const [map, setMap] = useState<any>(null);
  const { setUserInfo } = useGlobalContext();
  const [center, setCenter] = useState(defaultCenter);
  const [searchValue, setSearchValue] = useState("");
  const [address, setAddress] = useState<any>(true);
  const [place, setPlace] = useState<any>(null);
  const [formData, setFormData] = useState({
    locationType: "home",
    houseNo: "",
    floor: "",
    area: "",
    city: "",
    landmark: "",
  });

  const handleChange = (key: any) => (e: any) => {
    setFormData((prev) => ({
      ...prev,
      [key]: e.target.value,
    }));
  };

  const handleSelectChange = (value: any) => {
    setFormData((prev) => ({
      ...prev,
      locationType: value,
    }));
  };

  useEffect(() => {
    return () => {
      setMap(null);
      setPlace(null);
      setSearchValue("");
    };
  }, []);

  const handlePlaceSelected = () => {
    if (!autocompleteRef.current) return;
    const place = autocompleteRef.current.getPlace();
    if (place?.geometry) {
      const newCenter = {
        lat: place.geometry.location.lat(),
        lng: place.geometry.location.lng(),
      };

      setSearchValue(place?.formatted_address);
      //   setPlace(place);
      setCenter(newCenter);
      //   setAddress({
      //     place: place.formatted_address,
      //     location: newCenter
      //   });
    }
  };
  const handleMapLoad = (mapInstance: any) => {
    setMap(mapInstance);

    if (defaultCenter?.lat && defaultCenter?.lng && window.google?.maps) {
      const geocoder = new window.google.maps.Geocoder();
      geocoder.geocode({ location: defaultCenter }, (results, status) => {
        if (status === "OK" && results && results[0]) {
          const formatted_address = results[0].formatted_address;
          const address_components = results[0].address_components;

          setSearchValue(formatted_address);
          //   setAddress({
          //     place: formatted_address,
          //     location: defaultCenter
          //   });
          setPlace({
            geometry: {
              location: {
                lat: () => defaultCenter.lat,
                lng: () => defaultCenter.lng,
              },
            },
            formatted_address,
            address_components,
          });
        }
      });
    }
  };
  const handleAddressSave = () => {
    const addressComponents = place?.address_components || [];

    const getComponent = (type: string) => {
      const component = addressComponents.find((comp: any) =>
        comp.types.includes(type)
      );
      return component ? component.long_name : "";
    };
    const houseNo = getComponent("premise");
    const sublocality =
      getComponent("sublocality_level_1") || getComponent("sublocality");
    const sublocality2 = getComponent("sublocality_level_2");
    const city = getComponent("locality");
    setFormData((prev) => ({
      ...prev,
      area: sublocality || sublocality2 || "",
      city: city || "",
      houseNo: houseNo || "",
    }));
    setAddress(false);
    // setIsOpen(false);
  };

  const saveAdress = async () => {
    const addressData = {
      name: place?.formatted_address,
      building_no: formData.houseNo,
      tower: formData.floor,
      area: formData.area,
      city: formData.city,
      nearby_landmark: formData.landmark,
      lat: center?.lat,
      long: center?.lng,
      type: formData.locationType,
    };
    try {
      const apiRes = await apis.Profile.addAddress(addressData);
      if (apiRes) {
        handleCurrentaddress(apiRes?.data);
        setIsOpen(false);
        window.dispatchEvent(new Event("addresses-updated"));
      }
    } catch (error) {}
  };
  const handleCurrentaddress = async (data: any) => {
    try {
      const apiRes = await apis.Profile.addCurrentAddress(data?._id);
      if (apiRes) {
        setUserInfo((prev: any) => ({
          ...prev,
          current_address: data,
        }));
      }
    } catch (error) {}
  };

  return (
    <Modal
      isOpen={isOpen}
      description=""
      onClose={() => setIsOpen(false)}
      title={title}
    >
      {address ? (
        <div>
          <LoadScript
            googleMapsApiKey={process.env.NEXT_PUBLIC_GOOGLE_MAP_KEY as string}
            libraries={libraries}
          >
            <div className="flex h-full w-full flex-col gap-2">
              <Autocomplete
                onLoad={(ref) => (autocompleteRef.current = ref)}
                onPlaceChanged={handlePlaceSelected}
              >
                <input
                  type="text"
                  placeholder="Enter an address"
                  className="w-full rounded border p-2"
                  value={searchValue}
                  onChange={(e) => setSearchValue(e.target.value)}
                />
              </Autocomplete>

              <div className="map-wrapper w-full" style={{ height: "100%" }}>
                {isOpen && (
                  <GoogleMap
                    center={center}
                    zoom={12}
                    mapContainerStyle={{ width: "100%", height: "400px" }}
                    onLoad={handleMapLoad}
                  >
                    <Marker
                      position={center}
                      draggable={true}
                      onDragEnd={(e) => {
                        const newLat = e.latLng?.lat();
                        const newLng = e.latLng?.lng();

                        if (newLat && newLng) {
                          const newCenter = { lat: newLat, lng: newLng };
                          setCenter(newCenter);

                          const geocoder = new window.google.maps.Geocoder();
                          geocoder.geocode(
                            { location: newCenter },
                            (results, status) => {
                              if (status === "OK" && results && results[0]) {
                                const formatted_address =
                                  results[0].formatted_address;
                                const address_components =
                                  results[0].address_components;

                                setSearchValue(formatted_address);
                                //   setAddress({
                                //     place: formatted_address,
                                //     location: newCenter
                                //   });
                                setPlace({
                                  geometry: {
                                    location: {
                                      lat: () => newLat,
                                      lng: () => newLng,
                                    },
                                  },
                                  formatted_address,
                                  address_components,
                                });
                              }
                            }
                          );
                        }
                      }}
                    />
                  </GoogleMap>
                )}
              </div>
            </div>
            <div className="flex justify-end my-1">
              <Button
                className="bg-primary text-white px-4 py-2 rounded w-full text-center"
                onClick={() => handleAddressSave()}
              >
                Save Address
              </Button>
            </div>
          </LoadScript>
        </div>
      ) : (
        <div>
          <Select
            value={formData.locationType}
            onValueChange={handleSelectChange}
          >
            <SelectTrigger
              id="location-type"
              placeholder="Select location type"
              className="w-full border rounded-md h-10 px-3 focus:ring-2 focus:ring-offset-0 focus:ring-blue-500"
            >
              <SelectValue placeholder="Select location type" />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectLabel className="text-xs text-gray-500 px-2 py-1.5">
                  Choose location type
                </SelectLabel>
                <SelectItem value="home" className="cursor-pointer">
                  Home
                </SelectItem>
                <SelectItem value="work" className="cursor-pointer">
                  Work
                </SelectItem>
                <SelectItem value="other" className="cursor-pointer">
                  Other
                </SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>

          <input
            type="text"
            placeholder="House No"
            className="w-full rounded border p-2 mt-2"
            value={formData.houseNo}
            onChange={handleChange("houseNo")}
          />
          <input
            type="text"
            placeholder="Floor / Tower"
            className="w-full rounded border p-2 mt-2"
            value={formData.floor}
            onChange={handleChange("floor")}
          />
          <input
            type="text"
            placeholder="Area/Sector/Locality"
            className="w-full rounded border p-2 mt-2"
            value={formData.area}
            onChange={handleChange("area")}
          />
          <input
            type="text"
            placeholder="City"
            className="w-full rounded border p-2 mt-2"
            value={formData.city}
            onChange={handleChange("city")}
          />
          <input
            type="text"
            placeholder="Add any nearby landmark"
            className="w-full rounded border p-2 mt-2"
            value={formData.landmark}
            onChange={handleChange("landmark")}
          />
          <Button
            className="bg-primary text-white px-4 py-2 rounded w-full text-center mt-2"
            onClick={saveAdress}
          >
            Save Address
          </Button>
        </div>
      )}
    </Modal>
  );
};
export default CheckoutAddress;
