import { Empty, TreeSelect } from "antd";
import { Title } from "./Title";
import { useMap } from "react-map-gl";
import getBbox from "@turf/bbox";
import { polygon as getPolygon } from "@turf/helpers";
import { api } from "../api";
import parse from "wellknown";
import { useQuery } from "@tanstack/react-query";

const { TreeNode } = TreeSelect;

const normalizeRegions = (rawRegions) => {
  return rawRegions.reduce((acc, ao) => {
    acc[ao.name] = ao;
    acc[ao.name].type = "ao";
    if (ao.rayons) {
      ao.rayons.forEach((rayon) => {
        acc[rayon.name] = rayon;
        acc[rayon.name].type = "rayon";
      });
    }
    return acc;
  }, {});
};

export const useGetRegions = () => {
  return useQuery(
    ["regions"],
    async () => {
      const { data } = await api.get("/api/ao_rayons/");
      return data;
    },
    {
      select: (rawRegions) => {
        return {
          raw: rawRegions,
          normalized: normalizeRegions(rawRegions),
        };
      },
      refetchOnWindowFocus: false,
      refetchOnMount: false
    }
  );
};

export const RegionSelect = ({
  disabled,
  value: selectedRegionId,
  onChange,
}) => {
  const { map } = useMap();
  const { data, isInitialLoading } = useGetRegions();

  const handleChange = (value) => {
    if (!value) return;

    const selectedRegion = data.normalized[value];
    const polygonWrapperGeom = parse(selectedRegion.polygon);

    const polygon = getPolygon(polygonWrapperGeom.coordinates[0]);
    const bbox = getBbox(polygon);

    onChange({ id: selectedRegion.name, geometry: polygon, type: selectedRegion.type });

    map.fitBounds(
      [
        [bbox[0], bbox[1]], // southwestern corner of the bounds
        [bbox[2], bbox[3]], // northeastern corner of the bounds
      ],
      {
        padding: 20,
      }
    );
  };

  const handleClear = () => onChange(null);

  return (
    <div>
      <Title text={"District / area"} />
      <TreeSelect
        showSearch
        style={{ width: "100%" }}
        value={selectedRegionId}
        dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
        placeholder="Select district or area"
        allowClear
        treeDefaultExpandAll={false}
        onChange={handleChange}
        loading={isInitialLoading}
        treeNodeFilterProp="title"
        onClear={handleClear}
        notFoundContent={
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={"Not found"}
          />
        }
        disabled={disabled}
      >
        {data?.raw.map((ao) => {
          return (
            <TreeNode key={ao.name} value={ao.name} title={ao.name}>
              {ao.rayons?.map((rayon) => (
                <TreeNode key={rayon.name} value={rayon.name} title={rayon.name} />
              ))}
            </TreeNode>
          );
        })}
      </TreeSelect>
    </div>
  );
};
