import { useState } from "react";

import { useMutation } from "@apollo/client/react";
import { Button, Form, Popover, Select, Space } from "antd";
import dayjs from "../../utils/day";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_PARTS_DISPATCH } from "../../graphql/parts-dispatch.queries";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import { GenerateDocument } from "../../utils/RenderTemplate";
import { TemplateList } from "../../utils/TemplateConstants";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { logImEXEvent } from "../../firebase/firebase.utils.js";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly,
  currentUser: selectCurrentUser
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobLineDispatchButton);

export function JobLineDispatchButton({
  setSelectedLines,
  selectedLines,
  bodyshop,
  jobRO,
  job,
  currentUser,
  disabled
}) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const Templates = TemplateList("job_special", {
    ro_number: job.ro_number
  });
  const { t } = useTranslation();
  const [dispatchLines] = useMutation(INSERT_PARTS_DISPATCH);
  const notification = useNotification();

  const handleConvert = async (values) => {
    try {
      setLoading(true);
      //THIS HAS NOT YET BEEN TESTED. START BY FINISHING THIS FUNCTION.
      logImEXEvent("joblines_dispatch", {});
      const result = await dispatchLines({
        variables: {
          partsDispatch: {
            dispatched_at: dayjs(),
            employeeid: values.employeeid,
            jobid: job.id,
            dispatched_by: currentUser.email,
            parts_dispatch_lines: {
              data: selectedLines.map((l) => ({
                joblineid: l.id,
                quantity: l.part_qty
              }))
            }
          }
          //joblineids: selectedLines.map((l) => l.id),
        }
      });
      if (result.errors) {
        console.log("🚀 ~ handleConvert ~ result.errors:", result.errors);
        notification.error({
          title: t("parts_dispatch.errors.creating", {
            error: result.errors
          })
        });
      } else {
        setSelectedLines([]);
        await GenerateDocument(
          {
            name: Templates.parts_dispatch.key,
            variables: {
              id: result.data.insert_parts_dispatch_one.id
            }
          },
          {},
          "p",
          null,
          notification
        );
      }
      setVisible(false);
    } catch (error) {
      console.log("🚀 ~ handleConvert ~ error:", error);
      notification.error({
        title: t("parts_dispatch.errors.creating", {
          error: error
        })
      });
    } finally {
      setLoading(false);
    }
  };

  const popMenu = (
    <div>
      <Form layout="vertical" form={form} onFinish={handleConvert}>
        <Form.Item
          name={"employeeid"}
          label={t("timetickets.fields.employee")}
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <Select
            showSearch={{
              optionFilterProp: "label",
              filterOption: (input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }}
            style={{ width: 200 }}
            options={bodyshop.employees
              .filter((emp) => emp.active)
              .map((emp) => ({
                value: emp.id,
                key: emp.id,
                label: `${emp.first_name} ${emp.last_name}`
              }))}
          />
        </Form.Item>

        <Space wrap>
          <Button danger onClick={() => form.submit()} loading={loading} disabled={selectedLines.length === 0}>
            {t("general.actions.save")}
          </Button>
          <Button onClick={() => setVisible(false)}>{t("general.actions.cancel")}</Button>
        </Space>
      </Form>
    </div>
  );

  return (
    <Popover open={visible} content={popMenu}>
      <Button
        disabled={selectedLines.length === 0 || jobRO || disabled}
        loading={loading}
        onClick={() => setVisible(true)}
      >
        {t("joblines.actions.dispatchparts", { count: selectedLines.length })}
      </Button>
    </Popover>
  );
}
