"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,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import apis from "@/utils/apis";
import { useGlobalContext } from "@/context/Provider";
import { MapPin, Building, Search } from "lucide-react";

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 [place, setPlace] = useState<any>(null);
  const [isSaving, setIsSaving] = useState(false);
  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 updateAddressComponents = (addressComponents: any[]) => {
    if (!addressComponents) return;
    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 || prev.area,
      city: city || prev.city,
      houseNo: houseNo || prev.houseNo,
    }));
  };

  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);
      if (place?.address_components) {
        updateAddressComponents(place.address_components);
      }
    }
  };

  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,
          });
          updateAddressComponents(address_components);
        }
      });
    }
  };

  const saveAddress = async () => {
    if (!searchValue && !place?.formatted_address) {
      Toast.error("Please select a valid location on map!");
      return;
    }
    const addressData = {
      name: searchValue || 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 {
      setIsSaving(true);
      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);
    } finally {
      setIsSaving(false);
    }
  };

  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 (
    <div className="w-full bg-white rounded-2xl border border-gray-100 shadow-sm p-4 md:p-6">
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {/* Left Column: Map & Search */}
        <div className="lg:col-span-6 flex flex-col gap-3">
          <div className="flex items-center gap-2 text-sm font-semibold text-gray-800 mb-1">
            <MapPin className="w-4 h-4 text-primary" />
            <span>Select Location on Map</span>
          </div>

          <div className="relative w-full">
            <Autocomplete
              onLoad={(ref) => (autocompleteRef.current = ref)}
              onPlaceChanged={handlePlaceSelected}
            >
              <div className="relative">
                <input
                  type="text"
                  placeholder="Search for area, street name..."
                  className="w-full rounded-xl border border-gray-200 pl-10 pr-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary shadow-sm"
                  value={searchValue}
                  onChange={(e) => setSearchValue(e.target.value)}
                />
                <Search className="w-4 h-4 text-gray-400 absolute left-3.5 top-3.5 pointer-events-none" />
              </div>
            </Autocomplete>
          </div>

          <div className="map-wrapper w-full rounded-xl overflow-hidden border border-gray-200 shadow-inner h-[280px] lg:h-[380px]">
            {isOpen && (
              <GoogleMap
                center={center}
                zoom={14}
                mapContainerStyle={{ width: "100%", height: "100%" }}
                onLoad={handleMapLoad}
                options={{
                  disableDefaultUI: false,
                  zoomControl: true,
                  streetViewControl: false,
                }}
              >
                <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);

                      if (window.google?.maps) {
                        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,
                              });
                              updateAddressComponents(address_components);
                            }
                          }
                        );
                      }
                    }
                  }}
                />
              </GoogleMap>
            )}
          </div>
          <p className="text-xs text-gray-400 flex items-center gap-1">
            <MapPin className="w-3 h-3 text-gray-400 shrink-0" />
            Drag pin to adjust exact location
          </p>
        </div>

        {/* Right Column: Address Details Form */}
        <div className="lg:col-span-6 flex flex-col justify-between space-y-4">
          <div className="space-y-4">
            <div className="flex items-center gap-2 text-sm font-semibold text-gray-800">
              <Building className="w-4 h-4 text-primary" />
              <span>Address Details</span>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1.5">
                Save Address As
              </label>
              <Select
                value={formData.locationType}
                onValueChange={handleSelectChange}
              >
                <SelectTrigger className="w-full border border-gray-200 rounded-xl h-11 px-3 text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary">
                  <SelectValue placeholder="Select location type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectGroup>
                    <SelectItem value="home">Home</SelectItem>
                    <SelectItem value="work">Work</SelectItem>
                    <SelectItem value="other">Other</SelectItem>
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">
                  House / Flat / Building No.
                </label>
                <input
                  type="text"
                  placeholder="e.g. Flat 402, B-Block"
                  className="w-full rounded-xl border border-gray-200 p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
                  value={formData.houseNo}
                  onChange={handleChange("houseNo")}
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">
                  Floor / Tower (Optional)
                </label>
                <input
                  type="text"
                  placeholder="e.g. 4th Floor"
                  className="w-full rounded-xl border border-gray-200 p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
                  value={formData.floor}
                  onChange={handleChange("floor")}
                />
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">
                  Area / Sector / Locality
                </label>
                <input
                  type="text"
                  placeholder="e.g. Sector 74"
                  className="w-full rounded-xl border border-gray-200 p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
                  value={formData.area}
                  onChange={handleChange("area")}
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">
                  City
                </label>
                <input
                  type="text"
                  placeholder="e.g. Mohali"
                  className="w-full rounded-xl border border-gray-200 p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
                  value={formData.city}
                  onChange={handleChange("city")}
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">
                Nearby Landmark (Optional)
              </label>
              <input
                type="text"
                placeholder="e.g. Near CP67 Mall"
                className="w-full rounded-xl border border-gray-200 p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
                value={formData.landmark}
                onChange={handleChange("landmark")}
              />
            </div>
          </div>

          <div className="pt-2 flex gap-3">
            <Button
              type="button"
              variant="outline"
              className="w-1/3 rounded-xl py-3 text-sm border-gray-200 hover:bg-gray-50"
              onClick={() => setIsOpen(false)}
            >
              Cancel
            </Button>
            <Button
              type="button"
              disabled={isSaving}
              className="w-2/3 bg-primary hover:bg-primary/90 text-white font-semibold py-3 rounded-xl text-sm shadow-sm transition-all"
              onClick={saveAddress}
            >
              {isSaving ? "Saving..." : "Save Address"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddAddress;