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_TICKET } from "../../graphql/timetickets.queries";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectCurrentUser } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});
const mapDispatchToProps = (dispatch) => ({
  setTimeTicketContext: (context) => dispatch(setModalContext({ context: context, modal: "timeTicket" }))
});

export function TimeTicketsCommit({ currentUser, timeticket, setTimeTicketContext }) {
  const { t } = useTranslation();
  const [updateTimeTicket] = useMutation(UPDATE_TIME_TICKET);
  const notification = useNotification();

  const [loading, setLoading] = useState(false);
  const handleCommit = async () => {
    setLoading(true);
    try {
      const ticketUpdate = timeticket.committed_at
        ? { commited_by: null, committed_at: null }
        : {
            commited_by: currentUser.email,
            committed_at: dayjs()
          };

      const result = await updateTimeTicket({
        variables: {
          timeticketId: timeticket.id,
          timeticket: ticketUpdate
        },
        update(cache) {
          cache.modify({
            fields: {
              timeTickets(existingtickets, { readField }) {
                return existingtickets.map((ticket) => {
                  if (timeticket.id === readField("id", ticket)) {
                    return {
                      ...ticket,
                      ...ticketUpdate
                    };
                  }
                  return ticket;
                });
              }
            }
          });
        }
      });
      if (result.errors) {
        notification.error({
          title: t("timetickets.errors.creating", {
            message: JSON.stringify(result.errors)
          })
        });
      } else {
        setTimeTicketContext({
          context: {
            id: timeticket.id,
            timeticket: result.data.update_timetickets.returning[0]
          }
        });
        notification.success({
          title: t("timetickets.successes.committed")
        });
      }
    } catch {
      // NO OP
    } finally {
      setLoading(false);
    }
  };

  if (!timeticket?.id) return null;

  return (
    <Button onClick={handleCommit} loading={loading} disabled={!timeticket?.id}>
      {timeticket?.committed_at ? t("timetickets.actions.uncommit") : t("timetickets.actions.commitone")}
    </Button>
  );
}

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