import {
  MinusCircleTwoTone,
  PlusCircleTwoTone,
  SyncOutlined,
} from "@ant-design/icons";
import { Button, Card, Input, Space, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { TemplateList } from "../../utils/TemplateConstants";
import { alphaSort } from "../../utils/sorters";
import PartsDispatchExpander from "../parts-dispatch-expander/parts-dispatch-expander.component";
import PrintWrapperComponent from "../print-wrapper/print-wrapper.component";

const mapStateToProps = createStructuredSelector({
  jobRO: selectJobReadOnly,
  bodyshop: selectBodyshop,
});

const mapDispatchToProps = (dispatch) => ({});

export function PartDispatchTableComponent({
  bodyshop,
  jobRO,
  job,
  billsQuery,
  handleOnRowClick,
}) {
  const { t } = useTranslation();

  const [state, setState] = useState({
    sortedInfo: {},
  });
  // const search = queryString.parse(useLocation().search);
  // const selectedBill = search.billid;
  const [searchText, setSearchText] = useState("");

  const Templates = TemplateList("job_special");

  const { refetch } = billsQuery;

  const recordActions = (record) => (
    <Space wrap>
      <PrintWrapperComponent
        templateObject={{
          name: Templates.parts_dispatch.key,
          variables: { id: record.id },
        }}
      />
    </Space>
  );
  const columns = [
    {
      title: t("parts_dispatch.fields.number"),
      dataIndex: "number",
      key: "number",
      sorter: (a, b) => alphaSort(a.number, b.number),
      width: "10%",
      sortOrder:
        state.sortedInfo.columnKey === "number" && state.sortedInfo.order,
    },
    {
      title: t("timetickets.fields.employee"),
      dataIndex: "employeeid",
      key: "employeeid",
      sorter: (a, b) => alphaSort(a.employeeid, b.employeeid),
      sortOrder:
        state.sortedInfo.columnKey === "employeeid" && state.sortedInfo.order,
      render: (text, record) => {
        const e = bodyshop.employees.find((e) => e.id === record.employeeid);
        return `${e?.first_name || ""} ${e?.last_name || ""}`.trim();
      },
    },
    {
      title: t("parts_dispatch.fields.percent_accepted"),
      dataIndex: "percent_accepted",
      key: "percent_accepted",

      render: (text, record) =>
        record.parts_dispatch_lines.length > 0
          ? `
              ${(
                (record.parts_dispatch_lines.filter((l) => l.accepted_at)
                  .length /
                  record.parts_dispatch_lines.length) *
                100
              ).toFixed(0)}%`
          : "0%",
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      width: "10%",
      render: (text, record) => recordActions(record, true),
    },
  ];

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

  return (
    <Card
      title={t("parts_dispatch.labels.parts_dispatch")}
      extra={
        <Space wrap>
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>

          <Input.Search
            placeholder={t("general.labels.search")}
            value={searchText}
            onChange={(e) => {
              e.preventDefault();
              setSearchText(e.target.value);
            }}
          />
        </Space>
      }
    >
      <Table
        loading={billsQuery.loading}
        scroll={{
          x: true, // y: "50rem"
        }}
        expandable={{
          expandedRowRender: (record) => (
            <PartsDispatchExpander dispatch={record} job={job} />
          ),
          rowExpandable: (record) => true,

          expandIcon: ({ expanded, onExpand, record }) =>
            expanded ? (
              <MinusCircleTwoTone onClick={(e) => onExpand(record, e)} />
            ) : (
              <PlusCircleTwoTone onClick={(e) => onExpand(record, e)} />
            ),
        }}
        columns={columns}
        rowKey="id"
        dataSource={billsQuery.data ? billsQuery.data.parts_dispatch : []}
        onChange={handleTableChange}
      />
    </Card>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PartDispatchTableComponent);
