import Typography from "@/shared/ui/components/Typography/Typography";
import "./MapSection.scss";
import Paragraph from "@/shared/ui/components/Paragraph/Paragraph";
import MapSearch from "./MapSearch/MapSearch";
import dynamic from "next/dynamic";
import { apiInstance } from "@/shared/config/apiConfig";
import { IReport } from "@/shared/types/report-type";
import Switch from "./Switch/Switch";
import {
  ROAD_TYPES,
  ROAD_TYPES_COLORS,
} from "@/shared/variables/road-types";

const DynamicMap = dynamic(() => import("./HomeMap/HomeMap"), {
  ssr: false,
});

interface IMapSectionProps {
  searchParams: {
    ["тип-дороги"]: string;
    ["поиск-на-карте"]: string;
    ["поиск-рейтинг"]: string;
    ["страница-рейтинга"]: string;
  };
}

const MapSection: React.FC<IMapSectionProps> = async ({
  searchParams,
}: IMapSectionProps) => {
  const getReports = async (categories: string) => {
    const res = await apiInstance<IReport[]>(
      `/report/?category=${categories}`
    );

    return res.data;
  };

  const data =
    (await getReports(searchParams["тип-дороги"] || "1,2,3,4,5,6")) ||
    [];

  const setCategories = (category: string) => {
    if (searchParams["тип-дороги"] === undefined) {
      const categories = ["1", "2", "3", "4", "5", "6"];
      return categories.filter((cat) => cat !== category).join(",");
    }

    const categories = Array.from(searchParams["тип-дороги"]).filter(
      (part) => part !== ","
    );

    if (categories.includes(category))
      return categories.filter((cat) => cat !== category).join(",");

    categories.push(category);
    return categories.join(",");
  };

  return (
    <div className="map-section">
      <div className="map-section__header">
        <Typography element="h3">Карта дорог</Typography>
        <Paragraph>
          Будьте в курсе последних новостей о дорожном движении,
          строительствах и мероприятиях!
        </Paragraph>
      </div>

      <div className="map-section__categories">
        <ul>
          {[1, 2, 3].map((sw) => (
            <li key={sw}>
              <Switch
                defaultState={
                  searchParams["тип-дороги"]
                    ? searchParams["тип-дороги"]?.includes(
                        sw.toString()
                      )
                    : true
                }
                color={ROAD_TYPES_COLORS[sw]}
                href={`?${new URLSearchParams({
                  ["тип-дороги"]: setCategories(
                    sw.toString()
                  ) as string,
                  ["поиск-на-карте"]:
                    searchParams["поиск-на-карте"] || "",
                  ["поиск-рейтинг"]:
                    searchParams["поиск-рейтинг"] || "",
                  ["страница-рейтинга"]:
                    searchParams["страница-рейтинга"] || "",
                })}`}
              />
              <p>{ROAD_TYPES[sw]}</p>
            </li>
          ))}
        </ul>
        <ul>
          {[4, 5, 6].map((sw) => (
            <li key={sw}>
              <Switch
                defaultState={
                  searchParams["тип-дороги"]
                    ? searchParams["тип-дороги"]?.includes(
                        sw.toString()
                      )
                    : true
                }
                color={ROAD_TYPES_COLORS[sw]}
                href={`?${new URLSearchParams({
                  ["тип-дороги"]: setCategories(
                    sw.toString()
                  ) as string,
                  ["поиск-на-карте"]:
                    searchParams["поиск-на-карте"] || "",
                  ["поиск-рейтинг"]:
                    searchParams["поиск-рейтинг"] || "",
                  ["страница-рейтинга"]:
                    searchParams["страница-рейтинга"] || "",
                })}`}
              />
              <p>{ROAD_TYPES[sw]}</p>
            </li>
          ))}
        </ul>
      </div>

      <MapSearch searchParams={searchParams} />

      <div className="map-section__categories"></div>

      <DynamicMap reports={data} />
    </div>
  );
};

export default MapSection;
