import { SyncOutlined } from "@ant-design/icons";
import { useTreatments } from "@splitsoftware/splitio-react";
import {
  Button,
  Dropdown,
  Input,
  Menu,
  PageHeader,
  Space,
  Statistic,
  Table,
} from "antd";
import React, { 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 { Production_List_Status_Colors } = useTreatments(
    ["Production_List_Status_Colors"],
    {},
    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,
            technician,
            state,
            activeStatuses: bodyshop.md_ro_statuses.active_statuses,
          }).find((e) => e.key === k.key),
          width: k.width,
        };
      })) ||
      []
  );

  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;
    setColumns(columns.filter((i) => i.key !== key));
  };

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

  const headerItem = (col) => (
    <Dropdown
      className="prod-header-dropdown"
      overlay={
        <Menu onClick={removeColumn}>
          <Menu.Item key={col.key}>
            {t("production.actions.removecolumn")}
          </Menu.Item>
        </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);
  return (
    <div>
      <PageHeader
        title={
          <Space>
            <Statistic
              title={t("dashboard.titles.productionhours")}
              value={totalHrs}
            />
            <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}
            />
            <ProductionListSaveConfigButton
              columns={columns}
              tableState={state}
            />

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

            <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) return null;

              return {
                style: {
                  backgroundColor: `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),
              onHeaderCell: (column) => ({
                width: column.width,
                onResize: handleResize(index),
              }),
            };
          })}
          rowKey="id"
          loading={loading}
          dataSource={dataSource}
          // scroll={{ x: true }}
          onChange={handleTableChange}
        />
      </ReactDragListView.DragColumn>
    </div>
  );
}
export default connect(mapStateToProps, null)(ProductionListTable);
