"use client";

import "./HomeMap.scss";
import "leaflet/dist/leaflet.css";
import {
  MapContainer,
  Marker,
  Popup,
  TileLayer,
} from "react-leaflet";
import geo_green_icon from "./icons/geo-green.svg";
import geo_orange_icon from "./icons/geo-orange.svg";
import geo_pink_icon from "./icons/geo-pink.svg";
import geo_purple_icon from "./icons/geo-purple.svg";
import geo_red_icon from "./icons/geo-red.svg";
import geo_yellow_icon from "./icons/geo-yellow.svg";
import { DivIcon, Icon, LatLngTuple } from "leaflet";
import { StaticImageData } from "next/image";
import Link from "next/link";

interface ILocation {
  id: number;
  latitude: string;
  longitude: string;
  address: string;
}

interface IData {
  id: number;
  created_at: string;
  location: ILocation[];
  category: number;
  description: string;
  count_reviews: number;
  total_likes: number;
}

interface IHomeMapProps {
  data: IData[] | undefined;
}

const HomeMap: React.FC<IHomeMapProps> = ({
  data,
}: IHomeMapProps) => {
  const createCustomIcon = (icon: StaticImageData) => {
    const customIcon = new Icon({
      iconUrl: icon.src,
      iconSize: [32, 32],
    });

    return customIcon;
  };

  const icons: Record<string, DivIcon> = {
    1: createCustomIcon(geo_red_icon),
    2: createCustomIcon(geo_pink_icon),
    3: createCustomIcon(geo_purple_icon),
    4: createCustomIcon(geo_orange_icon),
    5: createCustomIcon(geo_green_icon),
    6: createCustomIcon(geo_yellow_icon),
  };

  const position = [42.8746, 74.606];

  return (
    <MapContainer
      center={position as LatLngTuple}
      zoom={14}
      scrollWheelZoom={false}
      className="home-map"
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      {data?.map((marker) => (
        <Marker
          key={marker.id}
          icon={icons[marker.category]}
          position={
            [
              +marker.location[0].latitude,
              +marker.location[0].longitude,
            ] as LatLngTuple
          }
        >
          <Popup>
            <Link href={`/report/${marker.location[0].id}`}>
              {marker.location[0].address}
            </Link>
          </Popup>
        </Marker>
      ))}
    </MapContainer>
  );
};

export default HomeMap;
