import { useLazyQuery } from "@apollo/client/react";
import { Button, Form, Modal } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { FIND_CONTRACT } from "../../graphql/cccontracts.queries";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectContractFinder } from "../../redux/modals/modals.selectors";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import ContractsFindModalComponent from "./contracts-find-modal.component";
import AlertComponent from "../alert/alert.component";

const mapStateToProps = createStructuredSelector({
  contractFinderModal: selectContractFinder
});

const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("contractFinder"))
});

export function ContractsFindModalContainer({ contractFinderModal, toggleModalVisible }) {
  const { t } = useTranslation();

  const { open } = contractFinderModal;

  const [form] = Form.useForm();

  //  const [updateJobLines] = useMutation(UPDATE_JOB_LINE);
  const [callSearch, { loading, error, data }] = useLazyQuery(FIND_CONTRACT);
  const handleFinish = async (values) => {
    logImEXEvent("contract_finder_search");

    //Execute contract find
    callSearch({
      variables: {
        plate: (values.plate && values.plate !== "" && values.plate) || undefined,
        time: values.time
      }
    });
  };

  useEffect(() => {
    if (open) {
      form.resetFields();
    }
  }, [open, form]);

  return (
    <Modal
      open={open}
      width="70%"
      title={t("contracts.labels.findermodal")}
      onCancel={() => toggleModalVisible()}
      onOk={() => toggleModalVisible()}
      destroyOnHidden
      forceRender
    >
      <Form form={form} layout="vertical" autoComplete="no" onFinish={handleFinish}>
        <ContractsFindModalComponent form={form} />
        <Button onClick={() => form.submit()} type="primary" loading={loading}>
          {t("general.labels.search")}
        </Button>
        {error && <AlertComponent type="error" title={JSON.stringify(error)} />}
        <ResponsiveTable
          loading={loading}
          columns={[
            {
              title: t("contracts.fields.agreementnumber"),
              dataIndex: "agreementnumber",
              key: "agreementnumber",

              render: (text, record) => (
                <Link to={`/manage/courtesycars/contracts/${record.id}`}>{record.agreementnumber || ""}</Link>
              )
            },
            {
              title: t("jobs.fields.ro_number"),
              dataIndex: "job.ro_number",
              key: "job.ro_number",
              render: (text, record) => <Link to={`/manage/jobs/${record.job.id}`}>{record.job.ro_number || ""}</Link>
            },
            {
              title: t("contracts.fields.driver"),
              dataIndex: "driver_ln",
              key: "driver_ln",
              render: (text, record) => `${record.driver_fn || ""} ${record.driver_ln || ""}`
            },
            {
              title: t("contracts.labels.vehicle"),
              dataIndex: "vehicle",
              key: "vehicle",
              render: (text, record) => (
                <Link to={`/manage/courtesycars/${record.courtesycar.id}`}>{`${
                  record.courtesycar.year
                } ${record.courtesycar.make} ${record.courtesycar.model} ${
                  record.courtesycar.plate ? `(${record.courtesycar.plate})` : ""
                }`}</Link>
              )
            },
            {
              title: t("contracts.fields.status"),
              dataIndex: "status",
              render: (text, record) => t(record.status)
            },
            {
              title: t("contracts.fields.start"),
              dataIndex: "start",
              key: "start",
              render: (text, record) => <DateTimeFormatter>{record.start}</DateTimeFormatter>
            },
            {
              title: t("contracts.fields.scheduledreturn"),
              dataIndex: "scheduledreturn",
              key: "scheduledreturn",
              render: (text, record) => <DateTimeFormatter>{record.scheduledreturn}</DateTimeFormatter>
            },
            {
              title: t("contracts.fields.actualreturn"),
              dataIndex: "actualreturn",
              key: "actualreturn",
              render: (text, record) => <DateTimeFormatter>{record.actualreturn}</DateTimeFormatter>
            }
          ]}
          mobileColumnKeys={["agreementnumber", "job.ro_number", "driver_ln", "status"]}
          rowKey="id"
          dataSource={data?.cccontracts}
        />
      </Form>
    </Modal>
  );
}

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