import { Button, Input, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { alphaSort } from "../../utils/sorters";
import AllocationsAssignmentContainer from "../allocations-assignment/allocations-assignment.container";
import AllocationsBulkAssignmentContainer from "../allocations-bulk-assignment/allocations-bulk-assignment.container";
import AllocationsEmployeeLabelContainer from "../allocations-employee-label/allocations-employee-label.container";
import PartsOrderModalContainer from "../parts-order-modal/parts-order-modal.container";

export default function JobLinesComponent({
  loading,
  refetch,
  jobLines,
  setSearchText,
  selectedLines,
  setSelectedLines,
  partsOrderModalVisible,
  jobId,
  setJobLineEditContext
}) {
  const [state, setState] = useState({
    sortedInfo: {}
  });
  const { t } = useTranslation();
  const setPartsModalVisible = partsOrderModalVisible[1];
  const columns = [
    {
      title: t("joblines.fields.unq_seq"),
      dataIndex: "unq_seq",
      key: "unq_seq",
      // onFilter: (value, record) => record.ro_number.includes(value),
      // filteredValue: state.filteredInfo.text || null,
      sorter: (a, b) => a.unq_seq - b.unq_seq,
      sortOrder:
        state.sortedInfo.columnKey === "unq_seq" && state.sortedInfo.order,
      //ellipsis: true,
      editable: true,
      width: 75
    },
    {
      title: t("joblines.fields.line_desc"),
      dataIndex: "line_desc",
      key: "line_desc",
      sorter: (a, b) => alphaSort(a.line_desc, b.line_desc),
      sortOrder:
        state.sortedInfo.columnKey === "line_desc" && state.sortedInfo.order,
      ellipsis: true,
      editable: true,
      width: "20%"
    },
    {
      title: t("joblines.fields.oem_partno"),
      dataIndex: "oem_partno",
      key: "oem_partno",
      sorter: (a, b) =>
        alphaSort(
          a.oem_partno ? a.oem_partno : a.op_code_desc,
          b.oem_partno ? b.oem_partno : b.op_code_desc
        ),
      sortOrder:
        state.sortedInfo.columnKey === "oem_partno" && state.sortedInfo.order,
      ellipsis: true,
      editable: true,
      width: "10%",
      render: (text, record) => (
        <span>
          {record.oem_partno ? record.oem_partno : record.op_code_desc}
        </span>
      )
    },
    {
      title: t("joblines.fields.part_type"),
      dataIndex: "part_type",
      key: "part_type",
      sorter: (a, b) => alphaSort(a.part_type, b.part_type),
      sortOrder:
        state.sortedInfo.columnKey === "part_type" && state.sortedInfo.order,
      ellipsis: true,
      editable: true,
      width: "7%"
    },
    {
      title: t("joblines.fields.line_ind"),
      dataIndex: "line_ind",
      key: "line_ind",
      sorter: (a, b) => alphaSort(a.line_ind, b.line_ind),
      sortOrder:
        state.sortedInfo.columnKey === "line_ind" && state.sortedInfo.order
    },
    {
      title: t("joblines.fields.db_price"),
      dataIndex: "db_price",
      key: "db_price",
      sorter: (a, b) => a.db_price - b.db_price,
      sortOrder:
        state.sortedInfo.columnKey === "db_price" && state.sortedInfo.order,
      ellipsis: true,
      width: "8%",
      render: (text, record) => (
        <CurrencyFormatter>{record.db_price}</CurrencyFormatter>
      )
    },
    {
      title: t("joblines.fields.act_price"),
      dataIndex: "act_price",
      key: "act_price",
      sorter: (a, b) => a.act_price - b.act_price,
      sortOrder:
        state.sortedInfo.columnKey === "act_price" && state.sortedInfo.order,
      ellipsis: true,
      width: "8%",
      render: (text, record) => (
        <CurrencyFormatter>{record.act_price}</CurrencyFormatter>
      )
    },
    {
      title: t("joblines.fields.mod_lb_hrs"),
      dataIndex: "mod_lb_hrs",
      key: "mod_lb_hrs",
      sorter: (a, b) => a.mod_lb_hrs - b.mod_lb_hrs,
      sortOrder:
        state.sortedInfo.columnKey === "mod_lb_hrs" && state.sortedInfo.order
    },
    {
      title: t("joblines.fields.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder:
        state.sortedInfo.columnKey === "status" && state.sortedInfo.order
    },
    {
      title: t("allocations.fields.employee"),
      dataIndex: "employee",
      key: "employee",
      width: "10%",
      sorter: (a, b) =>
        alphaSort(
          a.allocations[0] &&
            a.allocations[0].employee.first_name +
              a.allocations[0].employee.last_name,
          b.allocations[0] &&
            b.allocations[0].employee.first_name +
              b.allocations[0].employee.last_name
        ),
      sortOrder:
        state.sortedInfo.columnKey === "employee" && state.sortedInfo.order,
      render: (text, record) => (
        <span>
          {record.allocations && record.allocations.length > 0
            ? record.allocations.map(item => (
                <AllocationsEmployeeLabelContainer
                  key={item.id}
                  refetch={refetch}
                  allocation={item}
                />
              ))
            : null}
          <AllocationsAssignmentContainer
            key={record.id}
            refetch={refetch}
            jobLineId={record.id}
            hours={record.mod_lb_hrs}
          />
        </span>
      )
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      render: (text, record) => (
        <span>
          <Button
            onClick={() => {
              setJobLineEditContext({
                actions: { refetch: refetch },
                context: record
              });
            }}
          >
            {t("general.actions.edit")}
          </Button>
        </span>
      )
    }
  ];

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

  const formItemLayout = {
    labelCol: {
      xs: { span: 12 },
      sm: { span: 5 }
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 }
    }
  };

  return (
    <div>
      <PartsOrderModalContainer
        partsOrderModalVisible={partsOrderModalVisible}
        linesToOrder={selectedLines}
        refetch={refetch}
        jobId={jobId}
      />

      <Table
        title={() => {
          return (
            <div>
              <Input.Search
                placeholder={t("general.labels.search")}
                onChange={e => {
                  e.preventDefault();
                  setSearchText(e.target.value);
                }}
              />
              <Button
                disabled={selectedLines.length > 0 ? false : true}
                onClick={() => setPartsModalVisible(true)}
              >
                {t("parts.actions.order")}
              </Button>
              <AllocationsBulkAssignmentContainer
                jobLines={selectedLines}
                refetch={refetch}
              />
              <Button
                onClick={() => {
                  setJobLineEditContext({
                    actions: { refetch: refetch },
                    context: { jobid: jobId }
                  });
                }}
              >
                {t("joblines.actions.new")}
              </Button>
            </div>
          );
        }}
        {...formItemLayout}
        loading={loading}
        size="small"
        expandedRowRender={record => (
          <div style={{ margin: 0 }}>
            <strong>{t("parts_orders.labels.orderhistory")}</strong>
            {record.parts_order_lines.map(item => (
              <div key={item.id}>
                {`${item.parts_order.order_number || ""} from `}
                <Link to={`/manage/shop/vendors/${item.parts_order.vendor.id}`}>
                  {item.parts_order.vendor.name || ""}
                </Link>
                {` on ${item.parts_order.order_date || ""}`}
              </div>
            ))}
          </div>
        )}
        pagination={{ position: "top", defaultPageSize: 25 }}
        rowSelection={{
          // selectedRowKeys: selectedLines,
          onSelectAll: (selected, selectedRows, changeRows) => {
            setSelectedLines(selectedRows);
          },
          onSelect: (record, selected, selectedRows, nativeEvent) =>
            setSelectedLines(selectedRows)
        }}
        columns={columns.map(item => ({ ...item }))}
        rowKey="id"
        dataSource={jobLines}
        onChange={handleTableChange}
      />
    </div>
  );
}
