import { Button, Dropdown } from "antd";
import dataSource from "./production-list-columns.data";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";

const mapStateToProps = createStructuredSelector({
  technician: selectTechnician,
  bodyshop: selectBodyshop
});

const mapDispatchToProps = () => ({
  // Add any necessary dispatch actions here
});

export function ProductionColumnsComponent({
  columnState,
  technician,
  bodyshop,
  data,
  tableState,
  refetch,
  onColumnAdd
}) {
  const [columns, setColumns] = columnState;
  const { t } = useTranslation();
  const {
    treatments: { Enhanced_Payroll }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });

  const handleAdd = (e) => {
    const newColumn = dataSource({
      bodyshop,
      technician,
      state: tableState,
      data,
      activeStatuses: bodyshop.md_ro_statuses.active_statuses,
      treatments: { Enhanced_Payroll }
    }).find((i) => i.key === e.key);

    if (newColumn) {
      const updatedColumns = [...columns, newColumn];
      setColumns(updatedColumns);

      // Call the onColumnAdd function passed as a prop
      if (onColumnAdd) {
        onColumnAdd(newColumn);
      }
    }
  };

  const columnKeys = columns.map((i) => i.key);
  const cols = dataSource({
    bodyshop,
    technician,
    data,
    state: tableState,
    activeStatuses: bodyshop.md_ro_statuses.active_statuses,
    refetch,
    treatments: { Enhanced_Payroll }
  });

  const menu = {
    items: cols
      .filter((i) => !columnKeys.includes(i.key))
      .map((item) => ({
        key: item.key,
        label: item.title,
        style: { breakInside: "avoid" }
      })),
    style: {
      columnCount: Math.max(Math.floor(cols.length / 10), 1)
    },
    onClick: handleAdd
  };

  return (
    <div>
      <Dropdown menu={menu}>
        <Button>{t("production.actions.addcolumns")}</Button>
      </Dropdown>
    </div>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ProductionColumnsComponent);
