"use client";

import { useEffect, useRef, useState } from "react";
import {
  GoogleMap,
  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 AddAddress = ({
  title,
  isOpen,
  setIsOpen,
  defaultCenter,
  setAdd,
}: any) => {
  const autocompleteRef = useRef<any>(null);
  const [map, setMap] = useState<any>(null);
  const { setUserInfo, Toast } = 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);
    }
  };

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

  const saveAddress = 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) {
        await handleCurrentAddress(apiRes?.data);
        setAdd(false);
        setIsOpen(false);
        window.dispatchEvent(new Event("addresses-updated"));
      }
    } catch (error: any) {
      Toast.error(error);
      console.error("Failed to save address:", 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: any) {
      Toast.error(error);
    }
  };

  return (
    <>
      {address ? (
        <div>
          <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);
                              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>
        </div>
      ) : (
        <div>
          <Select
            value={formData.locationType}
            onValueChange={handleSelectChange}
          >
            <SelectTrigger className="w-full border rounded-md h-10 px-3 text-sm">
              <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">Home</SelectItem>
                <SelectItem value="work">Work</SelectItem>
                <SelectItem value="other">Other</SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>

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



      )}
    </>
  );
};

export default AddAddress;