import { useMutation, useLazyQuery } from "@apollo/client";
import { CheckCircleOutlined } from "@ant-design/icons";
import {
  Button,
  Card,
  Form,
  InputNumber,
  notification,
  Popover,
  Space,
} from "antd";
import moment from "moment";
import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import {
  INSERT_SCOREBOARD_ENTRY,
  QUERY_SCOREBOARD_ENTRY,
  UPDATE_SCOREBOARD_ENTRY,
} from "../../graphql/scoreboard.queries";
import FormDatePicker from "../form-date-picker/form-date-picker.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";

export default function ScoreboardAddButton({
  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
  );

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

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

  const handleFinish = async (values) => {
    logImEXEvent("job_close_add_to_scoreboard");

    setLoading(true);
    let result;

    if (entryData && 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"]({
        message: t("scoreboard.errors.adding", {
          message: JSON.stringify(result.errors),
        }),
      });
    } else {
      notification["success"]({
        message: 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"),
                },
              ]}
            >
              <FormDatePicker />
            </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 && entryData.scoreboard && entryData.scoreboard[0] && (
        <Space>
          <CheckCircleOutlined style={{ color: "green" }} />
          <span>{t("jobs.labels.alreadyaddedtoscoreboard")}</span>
        </Space>
      )}
    </Card>
  );

  const handleClick = (e) => {
    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,
      }
    );
    form.setFieldsValue({
      date: new moment(),
      bodyhrs: Math.round(v.bodyhrs * 10) / 10,
      painthrs: Math.round(v.painthrs * 10) / 10,
    });
    setVisibility(true);
    setLoading(false);
  };

  return (
    <Popover content={overlay} visible={visibility} placement="bottom">
      <Button
        loading={loading}
        disabled={disabled}
        onClick={handleClick}
        {...otherBtnProps}
      >
        {t("jobs.actions.addtoscoreboard")}
      </Button>
    </Popover>
  );
}
