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_TICKET } from "../../graphql/timetickets.queries";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";

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

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

  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: day()
          };

      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.open({
          type: "error",
          message: t("timetickets.errors.creating", {
            message: JSON.stringify(result.errors)
          })
        });
      } else {
        setTimeTicketContext({
          context: {
            id: timeticket.id,
            timeticket: result.data.update_timetickets.returning[0]
          }
        });
        notification.open({
          type: "success",
          message: t("timetickets.successes.committed")
        });
      }
    } catch (error) {
    } 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);
