import { CheckCircleOutlined } from "@ant-design/icons";
import { useLazyQuery, useMutation } from "@apollo/client/react";
import { Button, Card, Form, InputNumber, Popover, Space } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import {
  INSERT_SCOREBOARD_ENTRY,
  QUERY_SCOREBOARD_ENTRY,
  UPDATE_SCOREBOARD_ENTRY
} from "../../graphql/scoreboard.queries";
import { selectBodyshop } from "../../redux/user/user.selectors.js";
import dayjs from "../../utils/day";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component.jsx";
import DateTimePicker from "../form-date-time-picker/form-date-time-picker.component.jsx";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import LockWrapperComponent from "../lock-wrapper/lock-wrapper.component.jsx";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

export function ScoreboardAddButton({ bodyshop, job, disabled, ...otherBtnProps }) {
  const { t } = useTranslation();
  const [insertScoreboardEntry] = useMutation(INSERT_SCOREBOARD_ENTRY);
  const [updateScoreboardEntry] = useMutation(UPDATE_SCOREBOARD_ENTRY);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [visibility, setVisibility] = useState(false);
  const [callQuery, { loading: entryLoading, data: entryData }] = useLazyQuery(QUERY_SCOREBOARD_ENTRY);
  const notification = useNotification();

  useEffect(() => {
    if (visibility) {
      callQuery({ variables: { jobid: job.id } });
    }
  }, [visibility, job.id, callQuery]);

  useEffect(() => {
    if (entryData?.scoreboard && entryData.scoreboard[0]) {
      form.setFieldsValue(entryData.scoreboard[0]);
    }
  }, [entryData, form]);

  const handleFinish = async (values) => {
    logImEXEvent("job_close_add_to_scoreboard");
    values.date = dayjs(values.date).format("YYYY-MM-DD");

    setLoading(true);
    let result;

    if (entryData?.scoreboard && entryData.scoreboard[0]) {
      result = await updateScoreboardEntry({
        variables: {
          sbId: entryData.scoreboard[0].id,
          sbInput: values
        }
      });
    } else {
      result = await insertScoreboardEntry({
        variables: { sbInput: [{ jobid: job.id, ...values }] }
      });
    }

    if (result.errors) {
      notification.error({
        title: t("scoreboard.errors.adding", {
          message: JSON.stringify(result.errors)
        })
      });
    } else {
      notification.success({
        title: t("scoreboard.successes.added")
      });
    }
    setLoading(false);
    setVisibility(false);
  };

  const overlay = (
    <Card>
      <div>
        {entryLoading ? (
          <LoadingSpinner />
        ) : (
          <Form form={form} layout="vertical" onFinish={handleFinish} initialValues={{}}>
            <Form.Item
              label={t("scoreboard.fields.date")}
              name="date"
              rules={[
                {
                  required: true
                  //message: t("general.validation.required"),
                }
              ]}
            >
              <DateTimePicker isDateOnly />
            </Form.Item>
            <Form.Item
              label={t("scoreboard.fields.bodyhrs")}
              name="bodyhrs"
              rules={[
                {
                  required: true
                  //message: t("general.validation.required"),
                }
              ]}
            >
              <InputNumber precision={1} />
            </Form.Item>
            <Form.Item
              label={t("scoreboard.fields.painthrs")}
              name="painthrs"
              rules={[
                {
                  required: true
                  //message: t("general.validation.required"),
                }
              ]}
            >
              <InputNumber precision={1} />
            </Form.Item>

            <Space wrap>
              <Button type="primary" htmlType="submit">
                {t("general.actions.save")}
              </Button>
              <Button onClick={() => setVisibility(false)}>{t("general.actions.cancel")}</Button>
            </Space>
          </Form>
        )}
      </div>
      {entryData?.scoreboard && entryData.scoreboard[0] && (
        <Space>
          <CheckCircleOutlined style={{ color: "green" }} />
          <span>{t("jobs.labels.alreadyaddedtoscoreboard")}</span>
        </Space>
      )}
    </Card>
  );

  const handleClick = () => {
    setLoading(true);
    const v = job.joblines.reduce(
      (acc, val) => {
        if (val.mod_lbr_ty !== "LAR") acc = { ...acc, bodyhrs: acc.bodyhrs + val.mod_lb_hrs };
        if (val.mod_lbr_ty === "LAR") acc = { ...acc, painthrs: acc.painthrs + val.mod_lb_hrs };
        return acc;
      },
      {
        bodyhrs: 0,
        painthrs: 0
      }
    );

    //Add Labor Adjustments
    v.painthrs = v.painthrs + (job.lbr_adjustments.LAR || 0);
    v.bodyhrs =
      v.bodyhrs +
      Object.keys(job.lbr_adjustments)
        .filter((key) => key !== "LAR")
        .reduce((acc, val) => {
          return acc + job.lbr_adjustments[val];
        }, 0);
    form.setFieldsValue({
      date: dayjs(),
      bodyhrs: Math.round(v.bodyhrs * 10) / 10,
      painthrs: Math.round(v.painthrs * 10) / 10
    });
    setVisibility(true);
    setLoading(false);
  };
  const hasScoreboardAccess = HasFeatureAccess({ bodyshop, featureName: "scoreboard" });
  return (
    <Popover content={overlay} open={visibility} placement="bottom">
      <Button loading={loading} disabled={disabled || !hasScoreboardAccess} onClick={handleClick} {...otherBtnProps}>
        <LockWrapperComponent featureName="scoreboard">{t("jobs.actions.addtoscoreboard")}</LockWrapperComponent>
      </Button>
    </Popover>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ScoreboardAddButton);
