import { useMutation } from "@apollo/client";
import { Button, notification } from "antd";
import day from "../../utils/day";
import React, { 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 { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";

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

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

  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: day()
          }
        },
        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: day()
                    };
                  }
                  return ticket;
                });
              }
            }
          });
        }
      });
      if (result.errors) {
        notification.open({
          type: "error",
          message: t("timetickets.errors.creating", {
            message: JSON.stringify(result.errors)
          })
        });
      } else {
        notification.open({
          type: "success",
          message: t("timetickets.successes.committed")
        });
        if (!!completedCallback) completedCallback([]);
        if (!!loadingCallback) loadingCallback(false);
      }
    } catch (error) {
    } 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);
