"use client";

import "./MapSection.scss";
import Switch from "@/Entities/Switch/Switch";
import SectionHeader from "@/Shared/UI/SectionHeader/SectionHeader";
import SearchBar from "@/Features/SearchBar/SearchBar";
import HomeMap from "@/Features/HomeMap/HomeMap";
import { useEffect, useState } from "react";
import { useMapStore } from "./map.store";
import { useShallow } from "zustand/react/shallow";
import { useDebounce } from "use-debounce";
import { useRouter } from "next/navigation";

enum ESwitch {
  BUTTON,
  A,
}

interface IMapSection {
  [key: string]: string;
}

const MapSection: React.FC<IMapSection> = ({
  queryMap,
  queryRating,
  categories = "1,2,3,4,5,6",
}: IMapSection) => {
  const [searchLocation, setSearchLocation] =
    useState<string>(queryMap);
  const [query] = useDebounce(searchLocation, 500);
  const router = useRouter();
  const switches = [
    { title: "Разбитая дорога", category: "1", color: "#E64452" },
    { title: "В планах ремонта", category: "4", color: "#FFAC33" },
    { title: "Очаг аварийности", category: "2", color: "#C288E2" },
    { title: "Отремонтировано", category: "5", color: "#8FDE6A" },
    { title: "Локальный дефект", category: "3", color: "#87289D" },
    {
      title: "Локальный дефект исправлен'",
      category: "6",
      color: "#FED363",
    },
  ];

  const data = useMapStore(useShallow((state) => state.data));
  const getRatings = useMapStore(
    useShallow((state) => state.getRatings)
  );

  useEffect(() => {
    getRatings(categories);
  }, [categories]);

  useEffect(() => {
    router.push(
      `/?тип-дороги=${categories}${
        query ? `&карта-дорог=${query}` : ""
      }${queryRating ? `&рейтинг=${queryRating}` : ""}`,
      {
        scroll: false,
      }
    );
  }, [query, router, categories]);

  const setSearchParams = (category: string) => {
    const availableCategories: Record<string, number> = {
      "1": 1,
      "2": 2,
      "3": 3,
      "4": 4,
      "5": 5,
      "6": 6,
    };

    if (!categories || !availableCategories[category])
      return categories;

    if (categories?.includes(category)) {
      const updatedString = categories
        ?.replace(category + ",", "")
        .replace("," + category, "")
        .replace(category, "");

      return updatedString;
    } else {
      const newValue = category + ",";
      const updatedString = newValue + categories;
      return updatedString;
    }
  };

  return (
    <div className="map-section">
      <SectionHeader description="Yorem ipsum dolor sit amet, consectetur adipiscing elit.">
        Карта дорог
      </SectionHeader>

      <SearchBar
        value={searchLocation}
        setValue={setSearchLocation}
        placeholder="Введите город, село или регион"
      />

      <div className="map-section__filters">
        {switches.map((sw) => (
          <div key={sw.category} className="map-section__switch">
            <Switch
              defaultState={
                categories?.includes(sw.category) || categories === ""
              }
              href={`/?тип-дороги=${setSearchParams(sw.category)}`}
              type={ESwitch.A}
              color={sw.color}
            />
            <h4>{sw.title}</h4>
          </div>
        ))}
      </div>

      <HomeMap data={data?.results} />
    </div>
  );
};

export default MapSection;
