import { RegionSelect } from "./RegionSelect";
import { Button } from "antd";
import { ObjectTypesSelect } from "./ObjectTypesSelect";
import { PredictionSlider } from "./PredictionSlider";
import { LayersVisibility } from "./LayersVisibility";
import { useState } from "react";
import { api } from "../../api";
import { useFilters } from "../../stores/useFilters";
import {
  useHasManualEdits,
  usePointSelection,
} from "../../stores/usePointSelection";

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 {
    filters: { prediction, region, categories },
  } = useFilters();

  const [isExporting, setIsExporting] = useState(false);
  const hasManualEdits = useHasManualEdits();
  const { reset: resetSelection } = usePointSelection();

  const handleExport = async () => {
    setIsExporting(true);
    try {
      const params = {
        filters: {
          rate_from: prediction[0],
          rate_to: prediction[1],
        },
      };

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

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

      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 />
        <PredictionSlider />
        <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>
          {hasManualEdits ? (
            <Button
              type="text"
              block
              className={"mt-2"}
              onClick={resetSelection}
            >
              Отменить ручное редактирование
            </Button>
          ) : null}
        </div>
      </div>
    </div>
  );
};
