"use client";

import "./StatisticsTable.scss";
import { useStatisticsStore } from "./statistics.store";
import { useShallow } from "zustand/react/shallow";
import SearchForm from "@/features/SearchForm/SearchForm";
import chevron_down from "./icons/chevron-down.svg";
import arrows from "@/shared/icons/arrows.svg";
import Image from "next/image";
import { useEffect, useState } from "react";
import { useDebounce } from "use-debounce";
import { useRouter } from "@/shared/config/navigation";

interface IStatisticsTableProps {
  searchParams: {
    ["поиск-населенного-пункта"]: string;
  };
}

const StatisticsTable: React.FC<IStatisticsTableProps> = ({
  searchParams,
}: IStatisticsTableProps) => {
  const router = useRouter();
  const [location, setLocation] = useState<string>("city");
  const [queryStatistics, setQueryStatistics] = useState<string>(
    searchParams["поиск-населенного-пункта"] || ""
  );
  const [query] = useDebounce(queryStatistics, 500);
  const {
    error,
    isLoading,
    getStatistics,
    data: statistics,
  } = useStatisticsStore(useShallow((state) => state));
  const [sort, setSort] = useState<string>("broken_road_1");

  const [openPopup, setOpenPopup] = useState<boolean>(false);

  const handleSubmit = () => {};

  const params = [
    {
      param: "Добавлено дорог",
      handleClick() {
        setSort("broken_road_1");
      },
    },
    {
      param: "Локальных дефектов",
      handleClick() {
        setSort("local_defect_3");
      },
    },
    {
      param: "Очагов аварийности",
      handleClick() {
        setSort("hotbed_of_accidents_2");
      },
    },
    {
      param: "Локальных дефектов исправлено",
      handleClick() {
        setSort("local_defect_fixed_6");
      },
    },
    {
      param: "В планах ремонта",
      handleClick() {
        setSort("repair_plans_4");
      },
    },
    {
      param: "Отремонтировано",
      handleClick() {
        setSort("repaired_5");
      },
    },
  ];

  const getStatsByLocation = async (location: string) => {
    setLocation(location);
    getStatistics(location, sort, query);
  };

  useEffect(() => {
    getStatistics(location, sort, query);

    router.push(`/statistics?поиск-населенного-пункта=${query}`, {
      scroll: false,
    });
  }, [query, sort]);

  return (
    <div className="statistics-table">
      <SearchForm
        onChange={(e) => setQueryStatistics(e.target.value)}
        value={queryStatistics}
        placeholder="Введите населенный пункт"
        style={{ width: "100%" }}
        handleSubmit={handleSubmit}
      />

      {openPopup && (
        <div className="statistics-table__popup">
          <button
            className={
              location === "state"
                ? "statistics-table__popup-current"
                : ""
            }
            onClick={() => getStatsByLocation("state")}
          >
            Область
          </button>
          <button
            className={
              location === "city"
                ? "statistics-table__popup-current"
                : ""
            }
            onClick={() => getStatsByLocation("city")}
          >
            Город
          </button>
          <button
            className={
              location === "village"
                ? "statistics-table__popup-current"
                : ""
            }
            onClick={() => getStatsByLocation("village")}
          >
            Деревня
          </button>
        </div>
      )}

      <div className="statistics-table__wrapper">
        <table>
          <thead>
            <tr>
              <td>
                <button onClick={() => setOpenPopup((prev) => !prev)}>
                  Город
                  <Image src={chevron_down} alt=" Chevron Icon" />
                </button>
              </td>
              {params.map((param) => (
                <td key={param.param}>
                  <button onClick={param.handleClick}>
                    {param.param}
                    <Image src={arrows} alt=" Arrows Icon" />
                  </button>
                </td>
              ))}
            </tr>
          </thead>
          <tbody>
            {statistics.length ? (
              statistics.map((stat) => (
                <tr key={stat.name}>
                  <td id="statistics-table-stat-name">{stat.name}</td>
                  <td>{stat.broken_road_1}</td>
                  <td>{stat.local_defect_3}</td>
                  <td>{stat.hotbed_of_accidents_2}</td>
                  <td>{stat.local_defect_fixed_6}</td>
                  <td>{stat.repair_plans_4}</td>
                  <td>{stat.repaired_5}</td>
                </tr>
              ))
            ) : (
              <tr id="statistics-table__no-data-warning">
                <td>{error ? error : "Данных не найдено"}</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default StatisticsTable;
