import { STATUS_LABEL_MAPPER } from "../../config";
import { useEffect, useMemo } from "react";
import { useGetRegions } from "../../components/RegionSelect.jsx";
import { getRegionNameById } from "../../Map/Popup/mode-popup/config.js";
import { Button, Popover } from "antd";
import { AddressSearch } from "../../Map/AddressSearch.jsx";
import { SearchOutlined } from "@ant-design/icons";
import { useTable } from "../../stores/useTable.js";
import useLocalStorage from "../../hooks/useLocalStorage.js";
import { TrafficModal } from "../../Map/TrafficModal.jsx";
export const useColumns = (fields = [], key) => {
  const { data: regions } = useGetRegions();
  const {
    tableState: { fullScreen },
  } = useTable();

  const [sort, setSort] = useLocalStorage(`${key}Sort`, null);

  const defaultColumns = useMemo(() => {
    return [
      {
        title: fullScreen ? (
          <div className="flex items-center justify-between">
            <span>Адрес</span>
            <Popover
              content={<AddressSearch autoFocus={true} />}
              trigger="click"
              placement={"right"}
            >
              <Button onClick={(e) => e.stopPropagation()} >
                <SearchOutlined />
              </Button>
            </Popover>
          </div>
        ) : (
          "Адрес"
        ),
        name: "Адрес",
        dataIndex: "address",
        key: "address",
        width: 200,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Район",
        dataIndex: "area",
        key: "area",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
        render: (_, record) => {
          return getRegionNameById(record.area, regions?.normalized);
        },
      },
      {
        title: "Округ",
        dataIndex: "district",
        key: "district",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
        render: (_, record) => {
          return getRegionNameById(record.district, regions?.normalized);
        },
      },
      {
        title: "Название",
        dataIndex: "name",
        key: "name",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Категория",
        dataIndex: "category",
        key: "category",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Статус",
        dataIndex: "status",
        key: "status",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
        render: (_, record) => {
          return STATUS_LABEL_MAPPER[record.status];
        },
      },
      {
        title: "Прогнозный трафик",
        dataIndex: "prediction_current",
        key: "prediction_current",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
        render: (_, record) => <TrafficModal point={record} />
      },
      {
        title: "Кол-во подъездов в жилом доме",
        dataIndex: "doors",
        key: "doors",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Класс энероэффективности жилого дома",
        dataIndex: "enrg_cls",
        key: "enrg_cls",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во квартир в подъезде жилого дома",
        dataIndex: "flat_cnt",
        key: "flat_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Год постройки жилого дома",
        dataIndex: "year_bld",
        key: "year_bld",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во этажей жилого дома",
        dataIndex: "levels",
        key: "levels",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Материал стен жилого дома",
        dataIndex: "mat_nes",
        key: "mat_nes",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во постаматов других сетей в окрестности 500м (далее аналогично)",
        dataIndex: "rival_post_cnt",
        key: "rival_post_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во ПВЗ",
        dataIndex: "rival_pvz_cnt",
        key: "rival_pvz_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во постаматов Мой постамат",
        dataIndex: "target_post_cnt",
        key: "target_post_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во квартир в окрестности",
        dataIndex: "flats_cnt",
        key: "flats_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во достопримечательностей",
        dataIndex: "attraction_cnt",
        key: "attraction_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во банков",
        dataIndex: "bank_cnt",
        key: "bank_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во торговых центров",
        dataIndex: "tc_cnt",
        key: "tc_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во бизнес-центров",
        dataIndex: "bc_cnt",
        key: "bc_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во клиник",
        dataIndex: "clinic_cnt",
        key: "clinic_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во объектов культуры (театры, музей и тд)",
        dataIndex: "culture_cnt",
        key: "culture_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во спортивных центров",
        dataIndex: "sport_center_cnt",
        key: "sport_center_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во лабораторий",
        dataIndex: "lab_cnt",
        key: "lab_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во школ",
        dataIndex: "school_cnt",
        key: "school_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во детских садов",
        dataIndex: "kindergar_cnt",
        key: "kindergar_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во МФЦ",
        dataIndex: "mfc_cnt",
        key: "mfc_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во аптек",
        dataIndex: "pharmacy_cnt",
        key: "pharmacy_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во остановок ОТ",
        dataIndex: "public_stop_cnt",
        key: "public_stop_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во объектов из HORECA",
        dataIndex: "reca_cnt",
        key: "reca_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во супермаркетов",
        dataIndex: "supermarket_cnt",
        key: "supermarket_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Кол-во премиальных супермаркетов",
        dataIndex: "supermarket_premium_cnt",
        key: "supermarket_premium_cnt",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Расстояние до постамата Мой постамата",
        dataIndex: "target_dist",
        key: "target_dist",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Расстояние до метро",
        dataIndex: "metro_dist",
        key: "metro_dist",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Стоимость жилой недвижимости ",
        dataIndex: "property_price_bargains",
        key: "property_price_bargains",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Бизнес-активность",
        dataIndex: "business_activity",
        key: "business_activity",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Эра постройки жилой недвижимости",
        dataIndex: "property_era",
        key: "property_era",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Средняя этажность застройки",
        dataIndex: "property_mean_floor",
        key: "property_mean_floor",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      ...fields,
    ].filter(Boolean);
  }, [regions?.normalized, fields, fullScreen]);

  const [order, setOrder] = useLocalStorage(`${key}Order`, defaultColumns.map((column, index) => {
    return {
      key: column.key,
      position: index,
      show: true,
    }
  }));

  useEffect(() => {
    const newColumns = defaultColumns.filter((column) => {
      return !order.find(c => c.key === column.key);
    });
    const newOrderColumns = newColumns.map((column, index) => {
      return {
        key: column.key,
        position: defaultColumns.length - index - 1,
        show: true,
      }
    });
    setOrder([
      ...order,
      ...newOrderColumns
    ]);
  }, [defaultColumns]);

  const columns = useMemo(() => {
    return order.flatMap((item) => !item.show ? [] : defaultColumns[item.position])
      .map((column) => {
        if (sort && sort.includes(column?.key)) return {
          ...column,
          defaultSortOrder: sort.includes('-') ? 'descend' : 'ascend',
        };
        return column;
      }).filter(Boolean);
  }, [defaultColumns, order, fullScreen]);

  return {
    columns,
    orderColumns: {
      defaultColumns,
      order,
      setOrder,
    },
    sort,
    setSort
  };
};
