"use client";

import { IStatistics } from "@/shared/types/statistics-type";
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 "next/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 [filter, setFilter] = useState({
    option: "broken_road",
    toggle: false,
  });

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

  const handleSubmit = () => {};

  const params = [
    {
      param: "Добавлено дорог",
      async handleClick() {
        if (filter.option !== "broken_road_1") {
          return setFilter({
            option: "broken_road_1",
            toggle: false,
          });
        }

        setFilter((prev) => {
          return { option: "broken_road_1", toggle: !prev.toggle };
        });

        getStatistics(location, filter, query);
      },
    },
    {
      param: "Локальных дефектов",
      async handleClick() {
        if (filter.option !== "local_defect_3") {
          return setFilter({
            option: "local_defect_3",
            toggle: false,
          });
        }

        setFilter((prev) => {
          return { option: "local_defect_3", toggle: !prev.toggle };
        });

        getStatistics(location, filter, query);
      },
    },
    {
      param: "Очагов аварийности",
      async handleClick() {
        if (filter.option !== "hotbed_of_accidents_2") {
          return setFilter({
            option: "hotbed_of_accidents_2",
            toggle: false,
          });
        }

        setFilter((prev) => {
          return {
            option: "hotbed_of_accidents_2",
            toggle: !prev.toggle,
          };
        });

        getStatistics(location, filter, query);
      },
    },
    {
      param: "Локальных дефектов исправлено",
      async handleClick() {
        if (filter.option !== "local_defect_fixed_6") {
          return setFilter({
            option: "local_defect_fixed_6",
            toggle: false,
          });
        }

        setFilter((prev) => {
          return {
            option: "local_defect_fixed_6",
            toggle: !prev.toggle,
          };
        });

        getStatistics(location, filter, query);
      },
    },
    {
      param: "В планах ремонта",
      async handleClick() {
        if (filter.option !== "repair_plans_4") {
          return setFilter({
            option: "repair_plans_4",
            toggle: false,
          });
        }

        setFilter((prev) => {
          return { option: "repair_plans_4", toggle: !prev.toggle };
        });

        getStatistics(location, filter, query);
      },
    },
    {
      param: "Отремонтировано",
      async handleClick() {
        if (filter.option !== "repaired_5") {
          return setFilter({ option: "repaired_5", toggle: false });
        }

        setFilter((prev) => {
          return { option: "repaired_5", toggle: !prev.toggle };
        });

        getStatistics(location, filter, query);
      },
    },
  ];

  const getStatsByLocation = async (location: string) => {
    setLocation(location);
    getStatistics(location, filter, query);
    console.error("Error fetching statistics:", error);
  };

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

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

  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
                    : "Oops, looks like there is no data"}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default StatisticsTable;
