import React, { useEffect } from "react";
import { Collapse, Empty, Table as AntdTable } from "antd";
import "./Table.css";
import parse from "wellknown";
import { useMap } from "react-map-gl";
import { useClickedPointConfig } from "../../stores/useClickedPointConfig";
import scrollIntoView from "scroll-into-view-if-needed";
import { twMerge } from "tailwind-merge";
import { HeaderWrapper } from "./HeaderWrapper";
import { useTable } from "../../stores/useTable";

export const Table = React.memo(
  ({
    rowSelection,
    data,
    pageSize,
    isClickedPointLoading,
    page,
    onPageChange,
    columns,
    header,
    fullWidth,
    loading,
  }) => {
    const { clickedPointConfig } = useClickedPointConfig();
    const { map } = useMap();
    const { tableState, toggleOpened } = useTable();

    const SCROLL = {
      y: tableState.fullScreen ? "calc(100vh - 136px)" : "200px",
      x: "max-content",
    };

    useEffect(() => {
      if (clickedPointConfig === null || isClickedPointLoading) return;

      const row = document.querySelector(".scroll-row");
      if (row) {
        scrollIntoView(row, { behavior: "smooth" });
      }
    }, [clickedPointConfig, data]);

    return (
      <Collapse
        bordered={false}
        onChange={toggleOpened}
        activeKey={tableState.isOpened ? "opened" : null}
      >
        <Collapse.Panel
          key={"opened"}
          header={header ? header : <HeaderWrapper />}
          collapsible={tableState.fullScreen ? "disabled" : undefined}
        >
          <AntdTable
            size="small"
            locale={{ emptyText: <Empty description="Нет данных" /> }}
            pagination={{
              pageSize,
              current: page,
              onChange: onPageChange,
              total: data?.count,
              showSizeChanger: false,
              position: "bottomCenter",
            }}
            dataSource={data?.results}
            columns={columns}
            rowKey="location_id"
            scroll={SCROLL}
            sticky={true}
            onRow={(record) => {
              return {
                onClick: () => {
                  const geometry = parse(record.geometry);
                  map.flyTo({
                    center: [geometry.coordinates[0], geometry.coordinates[1]],
                    zoom: 13,
                    essential: true,
                  });
                },
              };
            }}
            rowSelection={rowSelection}
            rowClassName={(record) =>
              twMerge(
                "cursor-pointer",
                record.location_id === clickedPointConfig?.id && "scroll-row"
              )
            }
            data-fullwidth={fullWidth}
            loading={loading}
          />
        </Collapse.Panel>
      </Collapse>
    );
  }
);
