import { useLazyQuery } from "@apollo/client/react";
import { Button, Input, Modal, Table } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { SEARCH_DMS_VEHICLES } from "../../graphql/dms.queries";
import AlertComponent from "../alert/alert.component";

const mapStateToProps = createStructuredSelector({});

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

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

export function DmsCdkVehicles({ form, job }) {
  const [open, setOpen] = useState(false);
  const [selectedModel, setSelectedModel] = useState(null);
  const { t } = useTranslation();

  const [callSearch, { loading, error, data }] = useLazyQuery(SEARCH_DMS_VEHICLES);
  const columns = [
    {
      title: t("vehicles.fields.v_make_desc"),
      dataIndex: "make",
      key: "make"
    },
    {
      title: t("vehicles.fields.v_model_desc"),
      dataIndex: "model",
      key: "model"
    },
    {
      title: t("jobs.fields.dms.dms_make"),
      dataIndex: "makecode",
      key: "makecode"
    },
    {
      title: t("jobs.fields.dms.dms_model"),
      dataIndex: "modelcode",
      key: "modelcode"
    }
  ];

  return (
    <>
      <Modal
        width={"90%"}
        open={open}
        onCancel={() => setOpen(false)}
        onOk={() => {
          if (selectedModel) {
            form.setFieldsValue({
              dms_make: selectedModel.makecode,
              dms_model: selectedModel.modelcode
            });
            setOpen(false);
          }
        }}
        okButtonProps={{ disabled: !selectedModel }}
      >
        {error && <AlertComponent title={error.message} type="error" />}
        <Table
          title={() => (
            <Input.Search
              onSearch={(val) => callSearch({ variables: { search: val } })}
              placeholder={t("general.labels.search")}
              enterButton
            />
          )}
          columns={columns}
          loading={loading}
          rowKey="id"
          dataSource={data ? data.search_dms_vehicles : []}
          onRow={(record) => {
            return {
              onClick: () => setSelectedModel(record)
            };
          }}
          rowSelection={{
            onSelect: (record) => {
              setSelectedModel(record);
            },

            type: "radio",
            selectedRowKeys: [selectedModel?.id]
          }}
        />
      </Modal>
      <Button
        onClick={() => {
          setOpen(true);
          callSearch({
            variables: {
              search: job?.v_model_desc && job.v_model_desc.substr(0, 3)
            }
          });
        }}
      >
        {t("jobs.actions.dms.findmakemodelcode")}
      </Button>
    </>
  );
}
