import { ClockCircleOutlined } from "@ant-design/icons";
import { useApolloClient } from "@apollo/client/react";
import { Button, Card, Form, Popover, Select, Space, Tooltip } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { QUERY_JOB_LBR_ADJUSTMENTS, UPDATE_JOB } from "../../graphql/jobs.queries";

import _ from "lodash";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB_LINE } from "../../graphql/jobs-lines.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { selectIsPartsEntry } from "../../redux/application/application.selectors.js";

const mapStateToProps = createStructuredSelector({
  technician: selectTechnician,
  isPartsEntry: selectIsPartsEntry
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobLineConvertToLabor);

export function JobLineConvertToLabor({
  children,
  jobline,
  job,
  insertAuditTrail,
  technician,
  isPartsEntry,
  ...otherBtnProps
}) {
  const { t } = useTranslation();

  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [visibility, setVisibility] = useState(false);
  const client = useApolloClient();
  const notification = useNotification();

  const handleFinish = async (values) => {
    const { mod_lbr_ty } = values;
    logImEXEvent("job_convert_dollar_to_labor");

    setLoading(true);

    const existingAdjustments = await client.query({
      query: QUERY_JOB_LBR_ADJUSTMENTS,
      variables: {
        id: job.id
      }
    });

    const newAdjustments = _.cloneDeep(existingAdjustments.data.jobs_by_pk.lbr_adjustments);
    const adjustment = calculateAdjustment({ mod_lbr_ty, job, jobline });
    newAdjustments[mod_lbr_ty] = (newAdjustments[mod_lbr_ty] || 0) + adjustment;

    const jobUpdate = client.mutate({
      mutation: UPDATE_JOB,
      variables: {
        jobId: job.id,
        job: { lbr_adjustments: newAdjustments }
      }
    });

    const lineUpdate = client.mutate({
      mutation: UPDATE_JOB_LINE,
      variables: {
        lineId: jobline.id,
        line: {
          convertedtolbr: true,
          convertedtolbr_data: {
            mod_lbr_ty: mod_lbr_ty,
            mod_lb_hrs: adjustment
          }
        }
      }
    });

    if (jobUpdate.errors) {
      notification.error({
        title: t("jobs.errors.saving", {
          message: JSON.stringify(jobUpdate.errors)
        })
      });
      return;
    }
    if (lineUpdate.errors) {
      notification.error({
        title: t("joblines.errors.saving", {
          message: JSON.stringify(lineUpdate.errors)
        })
      });
      return;
    }
    insertAuditTrail({
      jobid: job.id,
      operation: AuditTrailMapping.jobmodifylbradj({
        hours: calculateAdjustment({ mod_lbr_ty, job, jobline }).toFixed(1),
        mod_lbr_ty
      }),
      type: "jobmodifylbradj"
    });
    setLoading(false);
    setVisibility(false);
  };

  const overlay = (
    <Card>
      <Form form={form} layout="vertical" onFinish={handleFinish}>
        <Form.Item
          label={t("joblines.fields.mod_lbr_ty")}
          name="mod_lbr_ty"
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <Select
            allowClear
            showSearch
            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 shouldUpdate>
          {() => {
            const { mod_lbr_ty } = form.getFieldsValue();
            return t("joblines.labels.adjustmenttobeadded", {
              adjustment: calculateAdjustment({
                mod_lbr_ty,
                job,
                jobline
              }).toFixed(1)
            });
          }}
        </Form.Item>

        <Space wrap>
          <Button type="primary" disabled={jobline.convertedtolbr} htmlType="submit">
            {t("general.actions.save")}
          </Button>
          <Button onClick={() => setVisibility(false)}>{t("general.actions.cancel")}</Button>
        </Space>
      </Form>
    </Card>
  );

  const handleClick = () => {
    setLoading(true);

    form.setFieldsValue({
      //   date: dayjs(),
      //   bodyhrs: Math.round(v.bodyhrs * 10) / 10,
      //   painthrs: Math.round(v.painthrs * 10) / 10,
    });
    setVisibility(true);
    setLoading(false);
  };

  return (
    <>
      {children}
      {!isPartsEntry && jobline.act_price !== 0 && !technician && (
        <Popover disabled={jobline.convertedtolbr} content={overlay} open={visibility} placement="bottom">
          <Tooltip title={t("joblines.actions.converttolabor")}>
            <Button
              type="link"
              disabled={jobline.convertedtolbr}
              loading={loading}
              onClick={handleClick}
              {...otherBtnProps}
              icon={<ClockCircleOutlined />}
            />
          </Tooltip>
        </Popover>
      )}
    </>
  );
}

function calculateAdjustment({ mod_lbr_ty, job, jobline }) {
  if (!mod_lbr_ty) return 0;
  const rate = job[`rate_${mod_lbr_ty.toLowerCase()}`];

  if (rate === 0 || rate === null || rate === undefined) return 0;
  const adj = jobline.act_price / job[`rate_${mod_lbr_ty.toLowerCase()}`];

  return adj;
}
