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}
              options={[
                { value: "LAA", label: t("joblines.fields.lbr_types.LAA") },
                { value: "LAB", label: t("joblines.fields.lbr_types.LAB") },
                { value: "LAD", label: t("joblines.fields.lbr_types.LAD") },
                { value: "LAE", label: t("joblines.fields.lbr_types.LAE") },
                { value: "LAF", label: t("joblines.fields.lbr_types.LAF") },
                { value: "LAG", label: t("joblines.fields.lbr_types.LAG") },
                { value: "LAM", label: t("joblines.fields.lbr_types.LAM") },
                { value: "LAR", label: t("joblines.fields.lbr_types.LAR") },
                { value: "LAS", label: t("joblines.fields.lbr_types.LAS") },
                { value: "LAU", label: t("joblines.fields.lbr_types.LAU") },
                { value: "LA1", label: t("joblines.fields.lbr_types.LA1") },
                { value: "LA2", label: t("joblines.fields.lbr_types.LA2") },
                { value: "LA3", label: t("joblines.fields.lbr_types.LA3") },
                { value: "LA4", label: t("joblines.fields.lbr_types.LA4") }
              ]}
            />
          </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>
  );
}
