import React, { useState } from "react";

import { useMutation } from "@apollo/client";
import { Button, Form, notification, 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";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly,
  currentUser: selectCurrentUser
});
const mapDispatchToProps = (dispatch) => ({
  //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 handleConvert = async (values) => {
    try {
      setLoading(true);
      //THIS HAS NOT YET BEEN TESTED. START BY FINISHING THIS FUNCTION.
      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.open({
          type: "error",
          message: 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"
        );
      }
      setVisible(false);
    } catch (error) {
      console.log("🚀 ~ handleConvert ~ error:", error);
      notification.open({
        type: "error",
        message: 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
            style={{ width: 200 }}
            optionFilterProp="children"
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            {bodyshop.employees
              .filter((emp) => emp.active)
              .map((emp) => (
                <Select.Option value={emp.id} key={emp.id} name={`${emp.first_name} ${emp.last_name}`}>
                  {`${emp.first_name} ${emp.last_name}`}
                </Select.Option>
              ))}
          </Select>
        </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>
  );
}
