"use client";
import React, { useState, useEffect } from "react";
import {
  Map,
  APIProvider,
  MapCameraChangedEvent,
  Marker,
} from "@vis.gl/react-google-maps";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import CryptoJS from "crypto-js";
import { History, LocateFixedIcon, Search, Signpost } from "lucide-react";
import Image from "next/image";
import usePlacesSearch from "@/hooks/usePlacesSearch";
import { ScrollArea } from "@/components/ui/scroll-area";
import clsx from "clsx";
import LineLoader from "@/components/Shared/LineLoader";

const center = {
  lat: 6.5244, // Default center (Lagos, Nigeria)
  lng: 3.3792,
};

// Encryption key (ensure to keep it secure)
const ENCRYPTION_KEY = "my-super-secret-key";

const encryptData = (data: any) => {
  return CryptoJS.AES.encrypt(JSON.stringify(data), ENCRYPTION_KEY).toString();
};

const decryptData = (ciphertext: string) => {
  const bytes = CryptoJS.AES.decrypt(ciphertext, ENCRYPTION_KEY);
  const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
  return JSON.parse(decryptedData);
};

const MapComponent = () => {
  const [currentPosition, setCurrentPosition] = useState(() => {
    const encryptedPosition =
      typeof window !== "undefined" && localStorage.getItem("user-location");
    if (encryptedPosition) {
      try {
        return decryptData(encryptedPosition);
      } catch (error) {
        console.error("Failed to decrypt location data", error);
        return center;
      }
    }
    return center;
  });

  const [search, setSearch] = useState("");
  const [isOpen, setIsOpen] = useState(true);

  const { places, fetchPlaceDetails, searchPlaces, isLoading } =
    usePlacesSearch(process.env.NEXT_PUBLIC_GOOGLE_API_KEY || "");

  useEffect(() => {
    if (currentPosition !== center) {
      const encryptedPosition = encryptData(currentPosition);
      localStorage.setItem("user-location", encryptedPosition);
    }
  }, [currentPosition]);

  const handleLocationClick = () => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const lat = position.coords.latitude;
        const lng = position.coords.longitude;
        const newPosition = { lat, lng };
        setCurrentPosition(newPosition);
      },
      (error) => {
        console.error("Error obtaining location", error);
        alert("Unable to access your location.");
      }
    );
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
    searchPlaces(e.target.value);
  };

  const handlePlaceSelect = async (placeId: string) => {
    const selectedPlace = await fetchPlaceDetails(placeId);
    if (selectedPlace?.geometry) {
      setSearch(
        //@ts-ignore
        selectedPlace.formatted_address
      );
      console.log(selectedPlace?.geometry);

      setCurrentPosition(selectedPlace.geometry.location);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogContent className="w-full bg-white max-w-screen min-h-screen !rounded-none h-screen">
        <DialogHeader>
          <DialogTitle className="font-semibold">
            <Image
              src={"/assets/images/waalook-icon.svg"}
              alt="logo"
              height={100}
              width={100}
              className="h-8 mx-auto"
            />
          </DialogTitle>
        </DialogHeader>
        <APIProvider
          apiKey={process.env.NEXT_PUBLIC_GOOGLE_API_KEY || ""}
          onLoad={() => console.log("Maps API has loaded.")}
        >
          <Map
            className="h-[calc(100vh-100px)]"
            zoom={13}
            center={currentPosition}
            backgroundColor={"var(--primary-50)"}
            mapId="90145a54c3c473ae"
          >
            <Marker position={currentPosition} />
          </Map>
        </APIProvider>

        <div className="absolute bg-white w-full sm:w-[350px] h-[55vh] space-y-4 right-0 p-4 top-0 bottom-0 sm:bottom-auto sm:top-32">
          <h4 className="">Search Location</h4>
          <div className="space-y-3">
            <Input
              className=""
              startIcon={<Search className="icon text-neutral-700" />}
              placeholder="Search for Location"
              value={search}
              onChange={handleSearchChange}
            />
            {places.length > 0 ? (
              <ScrollArea className="max-h-[calc(55vh-200px)]">
                <div className="divide-y max-h-[calc(55vh-200px)] h-full relative divide-neutral-300 text-sm">
                  {places.map((place, index) => (
                    <div
                      key={index}
                      role="button"
                      className="w-full flex py-3 items-center"
                      onClick={() => handlePlaceSelect(place.place_id)}
                    >
                      <Signpost className="icon mr-2 flex-shrink-0" />
                      <span>{place.description}</span>
                    </div>
                  ))}
                  <div
                    className={clsx(
                      !isLoading && "hidden",
                      "absolute transition bg-white/70 inset-0"
                    )}
                  >
                    <LineLoader />
                  </div>
                </div>
              </ScrollArea>
            ) : (
              <ScrollArea className="max-h-[calc(55vh-200px)]">
                <div className="max-h-[calc(55vh-200px)] divide-y divide-neutral-300 text-sm">
                  <div
                    role="button"
                    onClick={handleLocationClick}
                    className="w-full flex py-3 items-center"
                  >
                    <LocateFixedIcon className="icon mr-2" />
                    <span>Use Current Location</span>
                  </div>
                  <div className="py-3">
                    <h5 className="">Recent Searches</h5>

                    <div
                      role="button"
                      className="w-full flex py-3 items-center"
                    >
                      <History className="icon mr-2" />
                      <span>Use Current Location</span>
                    </div>
                    <div
                      role="button"
                      className="w-full flex py-3 items-center"
                    >
                      <History className="icon mr-2" />
                      <span>Use Current Location</span>
                    </div>
                    <div
                      role="button"
                      className="w-full flex py-3 items-center"
                    >
                      <History className="icon mr-2" />
                      <span>Use Current Location</span>
                    </div>
                    <div
                      role="button"
                      className="w-full flex py-3 items-center"
                    >
                      <History className="icon mr-2" />
                      <span>Use Current Location</span>
                    </div>
                  </div>
                  <div className="py-3">
                    <h5 className="">Saved Locations</h5>

                    <div
                      role="button"
                      className="w-full flex py-3 items-center"
                    >
                      <Signpost className="icon mr-2" />
                      <span>Use Current Location</span>
                    </div>
                    <div
                      role="button"
                      className="w-full flex py-3 items-center"
                    >
                      <Signpost className="icon mr-2" />
                      <span>Use Current Location</span>
                    </div>
                  </div>
                </div>
              </ScrollArea>
            )}
          </div>
          <Button
            onClick={() => setIsOpen(false)}
            className="absolute sm:static bottom-10 inset-x-5"
          >
            Confirm Location
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default MapComponent;
