import { Empty, TreeSelect } from "antd";
import { Title } from "../../components/Title";
import { useEffect, useMemo, useState } from "react";
import { useMap } from "react-map-gl";
import getBbox from "@turf/bbox";
import { polygon as getPolygon } from "@turf/helpers";
import { api } from "../../api";
import { useFilters } from "../../stores/useFilters";
import parse from "wellknown";

const { TreeNode } = TreeSelect;

const normalizeRegions = (rawRegions) => {
  if (!rawRegions) return {};

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

export const RegionSelect = ({ disabled }) => {
  const { map } = useMap();
  const {
    filters: { region },
    setRegion,
  } = useFilters();
  const [data, setData] = useState([]);
  const normalizedData = useMemo(() => normalizeRegions(data), [data]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const getRegions = async () => {
      setLoading(true);
      try {
        const response = await api.get("/api/ao_rayons");
        setData(response.data);
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    getRegions();
  }, []);

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

    const selectedRegion = normalizedData[value];

    const polygonWrapperGeom = parse(selectedRegion.polygon);

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

    setRegion({ id: value, 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 = () => setRegion(null);

  return (
    <div>
      <Title text={"АО / район"} />
      <TreeSelect
        showSearch
        style={{ width: "100%" }}
        value={region?.id}
        dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
        placeholder="Выберите АО или район"
        allowClear
        treeDefaultExpandAll={false}
        onChange={onChange}
        loading={loading}
        treeNodeFilterProp="title"
        onClear={handleClear}
        notFoundContent={
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={"Не найдено"}
          />
        }
        disabled={disabled}
      >
        {data?.map((ao) => {
          return (
            <TreeNode key={ao.id} value={ao.id} title={ao.name}>
              {ao.rayons?.map((rayon) => (
                <TreeNode key={rayon.id} value={rayon.id} title={rayon.name} />
              ))}
            </TreeNode>
          );
        })}
      </TreeSelect>
    </div>
  );
};
