import { RegionSelect } from "./RegionSelect";
import { Button } from "antd";
import { ObjectTypesSelect } from "./ObjectTypesSelect";
import { RatingSlider } from "./RatingSlider";
import { LayersVisibility } from "./LayersVisibility";
import { useFactors } from "../../stores/useFactors";
import { useActiveTypes } from "../../stores/useActiveTypes";
import { useRegion } from "../../stores/useRegion";
import { useGridSize } from "../../stores/useGridSize";
import { useRating } from "../../stores/useRating";
import { useState } from "react";
import { useModel } from "../../stores/useModel";
import { api } from "../../api";

const activeTablesMapper = {
  net_3: ["point3", "net_3"],
  net_4: ["point4", "net_4"],
  net_5: ["point5", "net_5"],
};

function download(filename, data) {
  const downloadLink = window.document.createElement("a");
  downloadLink.href = window.URL.createObjectURL(
    new Blob([data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    })
  );
  downloadLink.download = filename;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
}

const getRegionParam = (regionId) => {
  if (!regionId) return null;

  const [type, id] = regionId.split("-");

  if (type === "ao") {
    return { msk_ao: Number(id) };
  }

  return { msk_rayon: Number(id) - 1 };
};

export const Sidebar = () => {
  const { factors } = useFactors();
  const { activeTypes } = useActiveTypes();
  const { region } = useRegion();
  const { gridSize } = useGridSize();
  const { rate: rateRange } = useRating();
  const { model } = useModel();

  const [isExporting, setIsExporting] = useState(false);

  const handleExport = async () => {
    setIsExporting(true);
    try {
      const params = {
        koefs: factors,
        tables: activeTablesMapper[gridSize],
        filters: {
          rate_from: rateRange[0],
          rate_to: rateRange[1],
        },
        method: model === "ml" ? "model" : "rate",
      };

      if (region) {
        params.filters = {
          ...params.filters,
          ...getRegionParam(region),
        };
      }

      if (activeTypes.length) {
        params.filters = {
          ...params.filters,
          category: activeTypes,
        };
      }

      const resp = await api.post("/api/raschet/", params, {
        responseType: "arraybuffer",
      });
      const blob = resp.data;

      download("postamates.xlsx", blob);
    } catch (err) {
      console.log("Произошла ошибка");
    } finally {
      setIsExporting(false);
    }
  };

  return (
    <div className="absolute top-[20px] left-[20px] bg-white-background w-[300px] rounded-xl p-3 max-h-[calc(100%-40px)] overflow-y-auto z-10">
      <div className="space-y-5">
        <LayersVisibility />
        <RegionSelect />
        <ObjectTypesSelect />
        <RatingSlider />
        <div>
          <Button
            type="primary"
            block
            className={"mt-2"}
            onClick={handleExport}
            loading={isExporting}
            disabled={true}
          >
            Экспорт данных
          </Button>
          <Button type="primary" block className={"mt-2"} disabled={true}>
            Взять в работу
          </Button>
        </div>
      </div>
    </div>
  );
};
