import { DeleteOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Popconfirm, Select } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_ACTIVE_PROD_LIST_VIEW } from "../../graphql/associations.queries";
import { UPDATE_SHOP } from "../../graphql/bodyshop.queries";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import ProductionListColumns from "../production-list-columns/production-list-columns.data";
import { useSplitTreatments } from "@splitsoftware/splitio-react";

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

export function ProductionListTable({ refetch, bodyshop, technician, currentUser, state, data, setColumns, setState }) {
  const { t } = useTranslation();
  const [updateDefaultProdView] = useMutation(UPDATE_ACTIVE_PROD_LIST_VIEW);
  const [updateShop] = useMutation(UPDATE_SHOP);

  const {
    treatments: { Enhanced_Payroll }
  } = useSplitTreatments({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });

  const handleSelect = async (value, option) => {
    setColumns(
      bodyshop.production_config
        .filter((pc) => pc.name === value)[0]
        .columns.columnKeys.map((k) => {
          return {
            ...ProductionListColumns({
              bodyshop,
              refetch,
              technician,
              state,
              data: data,
              activeStatuses: bodyshop.md_ro_statuses.active_statuses,
              treatments: { Enhanced_Payroll }
            }).find((e) => e.key === k.key),
            width: k.width
          };
        })
    );
    setState(bodyshop.production_config.filter((pc) => pc.name === value)[0].columns.tableState);

    const assoc = bodyshop.associations.find((a) => a.useremail === currentUser.email);

    if (assoc) {
      await updateDefaultProdView({
        variables: { assocId: assoc.id, view: value },
        update(cache) {
          cache.modify({
            id: cache.identify(bodyshop),
            fields: {
              associations(existingAssociations, { readField }) {
                return existingAssociations.map((a) => {
                  if (a.useremail !== currentUser.email) return a;
                  return { ...a, default_prod_list_view: value };
                });
              }
            }
          });
        }
      });
    }
  };

  const handleTrash = async (name) => {
    await updateShop({
      variables: {
        id: bodyshop.id,
        shop: {
          production_config: bodyshop.production_config.filter((b) => b.name !== name)
        }
      },
      awaitRefetchQueries: true
    });

    setColumns(
      bodyshop.production_config[0].columns.columnKeys.map((k) => {
        return {
          ...ProductionListColumns({
            technician,
            state,
            refetch,
            data: data,
            activeStatuses: bodyshop.md_ro_statuses.active_statuses,
            treatments: { Enhanced_Payroll }
          }).find((e) => e.key === k.key),
          width: k.width
        };
      })
    );

    setState(bodyshop.production_config[0].columns.tableState);
  };
  const assoc = bodyshop.associations.find((a) => a.useremail === currentUser.email);

  const defaultView = assoc && assoc.default_prod_list_view;
  return (
    <div style={{ width: "10rem" }}>
      <Select
        onSelect={handleSelect}
        placeholder={t("production.labels.selectview")}
        optionLabelProp="label"
        popupMatchSelectWidth={false}
        defaultValue={defaultView}
      >
        {bodyshop.production_config.map((config) => (
          <Select.Option key={config.name} label={config.name}>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center"
              }}
            >
              <span
                style={{
                  flex: 1,
                  maxWidth: "80%",
                  marginRight: "1rem",
                  textOverflow: "ellipsis"
                }}
              >
                {config.name}
              </span>

              <Popconfirm
                placement="right"
                title={t("general.labels.areyousure")}
                onConfirm={() => handleTrash(config.name)}
              >
                <DeleteOutlined
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                />
              </Popconfirm>
            </div>
          </Select.Option>
        ))}
      </Select>
    </div>
  );
}

export default connect(mapStateToProps, null)(ProductionListTable);
