import { Button, Checkbox, Col, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { socket } from "../../pages/dms/dms.container";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { alphaSort } from "../../utils/sorters";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(DmsCustomerSelector);

export function DmsCustomerSelector({ bodyshop }) {
  const { t } = useTranslation();
  const [customerList, setcustomerList] = useState([]);
  const [open, setOpen] = useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState(null);
  const [dmsType, setDmsType] = useState("cdk");

  socket.on("cdk-select-customer", (customerList, callback) => {
    setOpen(true);
    setDmsType("cdk");
    setcustomerList(customerList);
  });
  socket.on("pbs-select-customer", (customerList, callback) => {
    setOpen(true);
    setDmsType("pbs");
    setcustomerList(customerList);
  });

  const onUseSelected = () => {
    setOpen(false);
    socket.emit(`${dmsType}-selected-customer`, selectedCustomer);
    setSelectedCustomer(null);
  };

  const onUseGeneric = () => {
    setOpen(false);
    socket.emit(`${dmsType}-selected-customer`, bodyshop.cdk_configuration.generic_customer_number);
    setSelectedCustomer(null);
  };

  const onCreateNew = () => {
    setOpen(false);
    socket.emit(`${dmsType}-selected-customer`, null);
    setSelectedCustomer(null);
  };

  const cdkColumns = [
    {
      title: t("jobs.fields.dms.id"),
      dataIndex: ["id", "value"],
      key: "id"
    },
    {
      title: t("jobs.fields.dms.vinowner"),
      dataIndex: "vinOwner",
      key: "vinOwner",
      render: (text, record) => <Checkbox disabled checked={record.vinOwner} />
    },
    {
      title: t("jobs.fields.dms.name1"),
      dataIndex: ["name1", "fullName"],
      key: "name1",
      sorter: (a, b) => alphaSort(a.name1 && a.name1.fullName, b.name1 && b.name1.fullName)
    },

    {
      title: t("jobs.fields.dms.address"),
      //dataIndex: ["name2", "fullName"],
      key: "address",
      render: (record, value) =>
        `${
          record.address && record.address.addressLine && record.address.addressLine[0]
        }, ${record.address && record.address.city} ${
          record.address && record.address.stateOrProvince
        } ${record.address && record.address.postalCode}`
    }
  ];

  const pbsColumns = [
    {
      title: t("jobs.fields.dms.id"),
      dataIndex: "ContactId",
      key: "ContactId"
    },
    {
      title: t("jobs.fields.dms.name1"),
      key: "name1",
      sorter: (a, b) => alphaSort(a.LastName, b.LastName),
      render: (text, record) => `${record.FirstName || ""} ${record.LastName || ""}`
    },

    {
      title: t("jobs.fields.dms.address"),
      key: "address",
      render: (record, value) => `${record.Address}, ${record.City} ${record.State} ${record.ZipCode}`
    }
  ];

  if (!open) return null;
  return (
    <Col span={24}>
      <Table
        title={() => (
          <div>
            <Button onClick={onUseSelected} disabled={!selectedCustomer}>
              {t("jobs.actions.dms.useselected")}
            </Button>
            <Button
              onClick={onUseGeneric}
              disabled={!(bodyshop.cdk_configuration && bodyshop.cdk_configuration.generic_customer_number)}
            >
              {t("jobs.actions.dms.usegeneric")}
            </Button>
            <Button onClick={onCreateNew}>{t("jobs.actions.dms.createnewcustomer")}</Button>
          </div>
        )}
        pagination={{ position: "top" }}
        columns={dmsType === "cdk" ? cdkColumns : pbsColumns}
        rowKey={(record) => (dmsType === "cdk" ? record.id.value : record.ContactId)}
        dataSource={customerList}
        //onChange={handleTableChange}
        rowSelection={{
          onSelect: (record) => {
            setSelectedCustomer(dmsType === "cdk" ? record.id.value : record.ContactId);
          },
          type: "radio",
          selectedRowKeys: [selectedCustomer]
        }}
      />
    </Col>
  );
}
