import { useMutation } from "@apollo/client/react";
import { Button, Card, Form, InputNumber, Popover, Select } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB } from "../../graphql/jobs.queries";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { insertAuditTrail } from "../../redux/application/application.actions";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});
export default connect(mapStateToProps, mapDispatchToProps)(LaborAllocationsAdjustmentEdit);

export function LaborAllocationsAdjustmentEdit({
  insertAuditTrail,
  jobId,
  mod_lbr_ty,
  adjustments,
  children,
  refetchQueryNames
}) {
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [updateAdjustments] = useMutation(UPDATE_JOB);
  const [form] = Form.useForm();
  const notification = useNotification();

  const { t } = useTranslation();

  const handleFinish = async (values) => {
    setLoading(true);
    const result = await updateAdjustments({
      variables: {
        jobId: jobId,
        job: {
          lbr_adjustments: {
            ...adjustments,
            [values.mod_lbr_ty]: values.hours
          }
        }
      },
      ...(refetchQueryNames ? { refetchQueries: refetchQueryNames } : {})
    });

    if (result.errors) {
      notification.error({
        title: t("jobs.errors.saving", {
          message: JSON.stringify(result.errors)
        })
      });
    } else {
      notification.success({
        title: t("jobs.successes.save")
      });
      insertAuditTrail({
        jobid: jobId,
        operation: AuditTrailMapping.jobmodifylbradj({
          mod_lbr_ty: values.mod_lbr_ty,
          hours: values.hours - ((adjustments && adjustments[mod_lbr_ty]) || 0).toFixed(1)
        }),
        type: "jobmodifylbradj"
      });
    }
    setLoading(false);
    setOpen(false);
  };

  const overlay = (
    <Card>
      <div>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFinish}
          initialValues={{
            mod_lbr_ty: mod_lbr_ty,
            hours: adjustments?.[mod_lbr_ty]
          }}
        >
          <Form.Item
            name="mod_lbr_ty"
            label={t("joblines.fields.mod_lbr_ty")}
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
          >
            <Select allowClear disabled={!!mod_lbr_ty}>
              <Select.Option value="LAA">{t("joblines.fields.lbr_types.LAA")}</Select.Option>
              <Select.Option value="LAB">{t("joblines.fields.lbr_types.LAB")}</Select.Option>
              <Select.Option value="LAD">{t("joblines.fields.lbr_types.LAD")}</Select.Option>
              <Select.Option value="LAE">{t("joblines.fields.lbr_types.LAE")}</Select.Option>
              <Select.Option value="LAF">{t("joblines.fields.lbr_types.LAF")}</Select.Option>
              <Select.Option value="LAG">{t("joblines.fields.lbr_types.LAG")}</Select.Option>
              <Select.Option value="LAM">{t("joblines.fields.lbr_types.LAM")}</Select.Option>
              <Select.Option value="LAR">{t("joblines.fields.lbr_types.LAR")}</Select.Option>
              <Select.Option value="LAS">{t("joblines.fields.lbr_types.LAS")}</Select.Option>
              <Select.Option value="LAU">{t("joblines.fields.lbr_types.LAU")}</Select.Option>
              <Select.Option value="LA1">{t("joblines.fields.lbr_types.LA1")}</Select.Option>
              <Select.Option value="LA2">{t("joblines.fields.lbr_types.LA2")}</Select.Option>
              <Select.Option value="LA3">{t("joblines.fields.lbr_types.LA3")}</Select.Option>
              <Select.Option value="LA4">{t("joblines.fields.lbr_types.LA4")}</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            label={t("jobs.fields.adjustmenthours")}
            name="hours"
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
          >
            <InputNumber precision={1} />
          </Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            {t("general.actions.save")}
          </Button>
        </Form>
      </div>
    </Card>
  );

  return (
    <Popover
      getPopupContainer={(trigger) => trigger?.parentElement || document.body}
      open={open}
      onOpenChange={(vis) => setOpen(vis)}
      content={overlay}
      trigger="click"
    >
      {children}
    </Popover>
  );
}
