import { MinusCircleTwoTone, PlusCircleTwoTone, SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
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({
  bodyshop: selectBodyshop
});

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

export function PartDispatchTableComponent({ bodyshop, job, billsQuery }) {
  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", job);

  const { refetch } = billsQuery;

  const recordActions = (record) => (
    <Space wrap>
      <PrintWrapperComponent
        templateObject={{
          name: Templates.parts_dispatch.key,
          variables: { id: record.id }
        }}
        messageObject={{ subject: Templates.parts_dispatch.subject }}
      />
    </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()} icon={<SyncOutlined />} />
          <Input.Search
            placeholder={t("general.labels.search")}
            value={searchText}
            onChange={(e) => {
              e.preventDefault();
              setSearchText(e.target.value);
            }}
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={billsQuery.loading}
        scroll={{
          x: true // y: "50rem"
        }}
        expandable={{
          expandedRowRender: (record) => <PartsDispatchExpander dispatch={record} job={job} />,
          rowExpandable: () => true,

          expandIcon: ({ expanded, onExpand, record }) =>
            expanded ? (
              <MinusCircleTwoTone onClick={(e) => onExpand(record, e)} />
            ) : (
              <PlusCircleTwoTone onClick={(e) => onExpand(record, e)} />
            )
        }}
        columns={columns}
        mobileColumnKeys={["number", "employeeid", "percent_accepted", "actions"]}
        rowKey="id"
        dataSource={billsQuery.data ? billsQuery.data.parts_dispatch : []}
        onChange={handleTableChange}
      />
    </Card>
  );
}

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