"use client";

import "./MapSection.scss";
import SearchForm from "@/features/SearchBar/SearchForm";
import { useEffect, useState } from "react";
import SectionHeader from "@/entities/SectionHeader/SectionHeader";
import {
  ROAD_TYPES,
  ROAD_TYPES_COLORS,
} from "@/shared/variables/road-types";
import HomeMap from "./HomeMap/HomeMap";
import { useRouter } from "next/navigation";
import { useMapStore } from "./mapSectionStore";
import Switch from "./Switch/Switch";
import { useShallow } from "zustand/react/shallow";

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

const MapSection: React.FC<IMapSectionProps> = ({
  categories = "1,2,3,4,5,6",
  queryMap,
  queryRating,
}: IMapSectionProps) => {
  const [mapSearch, setMapSearch] = useState<string>(queryMap || "");
  const data = useMapStore(useShallow((state) => state.data));
  const getReports = useMapStore(
    useShallow((state) => state.getReports)
  );
  const router = useRouter();

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

  const handleSubmit: React.FormEventHandler<
    HTMLFormElement
  > = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    setMapSearch(formData.get("map-search") as string);

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

  const setSearchParams = (category: string) => {
    const availableCategories = ["1", "2", "3", "4", "5", "6"];

    if (!categories || !availableCategories.includes(category))
      return categories;

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

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

  return (
    <section className="map-section">
      <SectionHeader
        title="Карта дорог"
        description="Будьте в курсе последних новостей о дорожном движении, строительствах и мероприятиях!"
      />
      <SearchForm
        onChange={(e) => setMapSearch(e.target.value)}
        name="map-search"
        value={mapSearch}
        placeholder="Введите город, село или регион"
        handleSubmit={handleSubmit}
      />
      <div className="map-section__categories">
        <ul className="map-section__categories_left">
          {[1, 2, 3].map((sw) => (
            <li key={sw}>
              <Switch
                href={`/?тип-дороги=${setSearchParams(
                  sw.toString()
                )}`}
                color={ROAD_TYPES_COLORS[sw]}
                defaultState={categories.includes(sw.toString())}
              />
              <label>{ROAD_TYPES[sw]}</label>
            </li>
          ))}
        </ul>
        <ul className="map-section__categories_right">
          {[4, 5, 6].map((sw) => (
            <li key={sw}>
              <Switch
                href={`/?тип-дороги=${setSearchParams(
                  sw.toString()
                )}`}
                color={ROAD_TYPES_COLORS[sw]}
                defaultState={categories.includes(sw.toString())}
              />
              <label>{ROAD_TYPES[sw]}</label>
            </li>
          ))}
        </ul>
      </div>

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

export default MapSection;
