import { SyncOutlined } from "@ant-design/icons";
import { useSplitTreatments } from "@splitsoftware/splitio-react";
import { Button, Dropdown, Input, Space, Statistic, Table } from "antd";
import { PageHeader } from "@ant-design/pro-layout";
import React, { useEffect, useMemo, useState } from "react";
import ReactDragListView from "react-drag-listview";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import ProductionListColumnsAdd from "../production-list-columns/production-list-columns.add.component";
import ProductionListColumns from "../production-list-columns/production-list-columns.data";
import ProductionListDetail from "../production-list-detail/production-list-detail.component";
import ProductionListSaveConfigButton from "../production-list-save-config-button/production-list-save-config-button.component";
import ProductionListPrint from "./production-list-print.component";
import ProductionListTableViewSelect from "./production-list-table-view-select.component";
import ResizeableTitle from "./production-list-table.resizeable.component";

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

export function ProductionListTable({ loading, data, refetch, bodyshop, technician, currentUser }) {
  const [searchText, setSearchText] = useState("");

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

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

  const defaultView = assoc && assoc.default_prod_list_view;

  const [state, setState] = useState(
    (bodyshop.production_config &&
      bodyshop.production_config.find((p) => p.name === defaultView)?.columns.tableState) ||
      bodyshop.production_config[0]?.columns.tableState || {
        sortedInfo: {},
        filteredInfo: { text: "" }
      }
  );

  const { t } = useTranslation();

  const matchingColumnConfig = useMemo(() => {
    return bodyshop.production_config.find((p) => p.name === defaultView);
  }, [bodyshop.production_config, defaultView]);

  const [columns, setColumns] = useState(
    (state &&
      matchingColumnConfig &&
      matchingColumnConfig.columns.columnKeys.map((k) => {
        return {
          ...ProductionListColumns({
            bodyshop,
            refetch,
            technician,
            state,
            data,
            activeStatuses: bodyshop.md_ro_statuses.active_statuses,
            treatments: { Production_List_Status_Colors, Enhanced_Payroll }
          }).find((e) => e.key === k.key),
          width: k.width ?? 100
        };
      })) ||
      []
  );

  useEffect(() => {
    const newColumns =
      (state &&
        matchingColumnConfig &&
        matchingColumnConfig.columns.columnKeys.map((k) => {
          return {
            ...ProductionListColumns({
              bodyshop,
              technician,
              refetch,
              state,
              data: data,
              activeStatuses: bodyshop.md_ro_statuses.active_statuses,
              treatments: { Production_List_Status_Colors, Enhanced_Payroll }
            }).find((e) => e.key === k.key),
            width: k.width ?? 100
          };
        })) ||
      [];
    setColumns(newColumns);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    //state,
    matchingColumnConfig,
    bodyshop,
    technician,
    data
  ]); //State removed from dependency array as it causes race condition when removing columns from table view and is not needed.

  const handleTableChange = (pagination, filters, sorter) => {
    setState({
      ...state,
      filteredInfo: filters,
      sortedInfo: { columnKey: sorter.columnKey, order: sorter.order }
    });
  };

  const onDragEnd = (fromIndex, toIndex) => {
    const columnsCopy = columns.slice();
    const item = columnsCopy.splice(fromIndex, 1)[0];
    columnsCopy.splice(toIndex, 0, item);
    setColumns(columnsCopy);
  };

  const removeColumn = (e) => {
    const { key } = e;
    const newColumns = columns.filter((i) => i.key !== key);
    setColumns(newColumns);
  };

  const handleResize =
    (index) =>
    (e, { size }) => {
      const nextColumns = [...columns];
      nextColumns[index] = {
        ...nextColumns[index],
        width: size.width
      };
      setColumns(nextColumns);
    };

  const headerItem = (col) => {
    const menu = {
      onClick: removeColumn,
      items: [
        {
          key: col.key,
          label: t("production.actions.removecolumn")
        }
      ]
    };

    return (
      <Dropdown className="prod-header-dropdown" menu={menu} trigger={["contextMenu"]}>
        <span>{col.title}</span>
      </Dropdown>
    );
  };

  const dataSource =
    searchText === ""
      ? data
      : data.filter(
          (j) =>
            (j.ro_number || "").toString().toLowerCase().includes(searchText.toLowerCase()) ||
            (j.ownr_co_nm || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.ownr_fn || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.ownr_ln || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.status || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.ins_co_nm || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.clm_no || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.v_model_desc || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.v_make_desc || "").toLowerCase().includes(searchText.toLowerCase())
        );

  // const handleSelectRecord = (record) => {
  //   if (selected !== record.id) {
  //     setSelected(record.id);
  //   } else {
  //     setSelected(null);
  //   }
  // };

  if (!!!columns) return <div>No columns found.</div>;

  const totalHrs = data
    .reduce(
      (acc, val) => acc + (val.labhrs?.aggregate?.sum?.mod_lb_hrs || 0) + (val.larhrs?.aggregate?.sum?.mod_lb_hrs || 0),
      0
    )
    .toFixed(1);
  const totalLAB = data.reduce((acc, val) => acc + (val.labhrs?.aggregate?.sum?.mod_lb_hrs || 0), 0).toFixed(1);
  const totalLAR = data.reduce((acc, val) => acc + (val.larhrs?.aggregate?.sum?.mod_lb_hrs || 0), 0).toFixed(1);
  return (
    <div>
      <PageHeader
        title={
          <Space>
            <Statistic title={t("dashboard.titles.productionhours")} value={totalHrs} />
            <Statistic title={t("dashboard.titles.labhours")} value={totalLAB} />
            <Statistic title={t("dashboard.titles.larhours")} value={totalLAR} />
            <Statistic title={t("appointments.labels.inproduction")} value={dataSource && dataSource.length} />
          </Space>
        }
        extra={
          <Space wrap>
            <Button onClick={() => refetch && refetch()}>
              <SyncOutlined />
            </Button>
            <ProductionListColumnsAdd columnState={[columns, setColumns]} tableState={state} data={data} />
            <ProductionListSaveConfigButton columns={columns} tableState={state} />

            <ProductionListTableViewSelect
              state={state}
              setState={setState}
              setColumns={setColumns}
              refetch={refetch}
              data={data}
            />

            <Input
              onChange={(e) => setSearchText(e.target.value)}
              placeholder={t("general.labels.search")}
              value={searchText}
            />
            <ProductionListPrint />
          </Space>
        }
      />
      <ProductionListDetail jobs={dataSource} />
      <ReactDragListView.DragColumn onDragEnd={onDragEnd} nodeSelector="th" handleSelector=".prod-header-dropdown">
        <Table
          sticky
          pagination={false}
          size="small"
          {...(Production_List_Status_Colors.treatment === "on" && {
            onRow: (record, index) => {
              if (!bodyshop.md_ro_statuses.production_colors) return null;

              const color = bodyshop.md_ro_statuses.production_colors.find((x) => x.status === record.status);

              if (!color) {
                if (index % 2 === 0)
                  return {
                    style: {
                      backgroundColor: `rgb(236, 236, 236)`
                    }
                  };

                return null;
              }

              return {
                className: "rowWithColor",
                style: {
                  "--bgColor": `rgb(${color.color.r},${color.color.g},${color.color.b},${color.color.a})`
                }
              };
            }
          })}
          components={{
            header: {
              cell: ResizeableTitle
            }
          }}
          columns={columns.map((c, index) => {
            return {
              ...c,
              filteredValue: state.filteredInfo[c.key] || null,
              sortOrder: state.sortedInfo.columnKey === c.key && state.sortedInfo.order,
              title: headerItem(c),
              ellipsis: true,
              width: c.width ?? 100,
              onHeaderCell: (column) => ({
                width: column.width,
                onResize: handleResize(index)
              })
            };
          })}
          rowKey="id"
          loading={loading}
          dataSource={dataSource}
          scroll={{ x: 1000 }}
          onChange={handleTableChange}
        />
      </ReactDragListView.DragColumn>
    </div>
  );
}

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