import { useMutation } from "@apollo/client/react";
import { Button } from "antd";
import dayjs from "../../utils/day";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_TIME_TICKETS } from "../../graphql/timetickets.queries";
import { selectCurrentUser } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});

export function TimeTicketsCommit({ currentUser, timetickets, disabled, loadingCallback, completedCallback }) {
  const { t } = useTranslation();
  const [updateTimeTickets] = useMutation(UPDATE_TIME_TICKETS);
  const notification = useNotification();

  const [loading, setLoading] = useState(false);
  const handleCommit = async () => {
    setLoading(true);
    try {
      const result = await updateTimeTickets({
        variables: {
          timeticketIds: timetickets.map((ticket) => ticket.id),
          timeticket: {
            commited_by: currentUser.email,
            committed_at: dayjs()
          }
        },
        update(cache) {
          cache.modify({
            fields: {
              timeTickets(existingtickets, { readField }) {
                const modifiedIds = timetickets.map((ticket) => ticket.id);
                return existingtickets.map((ticket) => {
                  if (modifiedIds.includes(readField("id", ticket))) {
                    return {
                      ...ticket,
                      commited_by: currentUser.email,
                      committed_at: dayjs()
                    };
                  }
                  return ticket;
                });
              }
            }
          });
        }
      });
      if (result.errors) {
        notification.error({
          title: t("timetickets.errors.creating", {
            message: JSON.stringify(result.errors)
          })
        });
      } else {
        notification.success({
          title: t("timetickets.successes.committed")
        });
        if (completedCallback) completedCallback([]);
        if (loadingCallback) loadingCallback(false);
      }
    } catch {
      // NOP OP
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button onClick={handleCommit} loading={loading} disabled={disabled || timetickets?.length === 0}>
      {t("timetickets.actions.commit", { count: timetickets?.length })}
    </Button>
  );
}

export default connect(mapStateToProps, null)(TimeTicketsCommit);
