import {useGetRegions} from "../../../components/RegionSelect.jsx";
import {useMemo} from "react";
import {getRegionNameById} from "../../../Map/Popup/mode-popup/config.js";
import {SearchOutlined} from "@ant-design/icons";
import {Button, Popover} from "antd";
import {AddressSearch} from "../../../Map/AddressSearch.jsx";
import {useTable} from "../../../stores/useTable.js";
import useLocalStorage from "../../../hooks/useLocalStorage.js";

const DEFAULT_LENGTH = 11;
export const useColumns = (key) => {
  const {data: regions} = useGetRegions();
  const {
    tableState: {fullScreen},
  } = useTable();

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

  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",
        sorter: true,
        showSorterTooltip: false,
        width: 200,
      },
      {
        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,
        render: (_, record) => {
          return getRegionNameById(record.district, regions?.normalized);
        },
        sorter: true,
        showSorterTooltip: false,
      },
      {
        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: "plan_current",
        key: "plan_current",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Факт",
        dataIndex: "fact",
        key: "fact",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Расхождение с прогнозом",
        dataIndex: "delta_current",
        key: "delta_current",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Зрелость",
        dataIndex: "age_day",
        key: "age_day",
        width: "120px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
      {
        title: "Дата начала работы",
        dataIndex: "start_date",
        key: "start_date",
        width: "120px",
        sorter: true,
        showSorterTooltip: false,
        render: (value) => {
          if (!value) return "Нет данных";

          const date = new Date(value);
          return date.toLocaleDateString("ru");
        },
      },
      {
        title: "Id постамата",
        dataIndex: "postamat_id",
        key: "postamat_id",
        width: "70px",
        ellipsis: true,
        sorter: true,
        showSorterTooltip: false,
      },
    ];
  }, [regions?.normalized, fullScreen]);

  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;
      });
  }, [defaultColumns, order, fullScreen]);

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