import { useApolloClient } from "@apollo/client/react";
import { Button } from "antd";
import dayjs from "../../utils/day";
import { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_SCHEDULE_LOAD_DATA } from "../../graphql/appointments.queries";
import { selectCurrentUser } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(ScheduleVerifyIntegrity);

export function ScheduleVerifyIntegrity({ currentUser }) {
  const [loading, setLoading] = useState(false);

  const client = useApolloClient();
  const handleVerify = async () => {
    setLoading(true);
    const {
      data: { arrJobs, compJobs, prodJobs }
    } = await client.query({
      query: QUERY_SCHEDULE_LOAD_DATA,
      variables: { start: dayjs(), end: dayjs().add(180, "day") }
    });

    //check that the leaving jobs are either in the arriving list, or in production.
    const issues = [];

    compJobs.forEach((j) => {
      const inProdJobs = prodJobs.find((p) => p.id === j.id);
      const inArrJobs = arrJobs.find((p) => p.id === j.id);

      if (!(inProdJobs || inArrJobs)) {
        // NOT FOUND!
        issues.push(j);
      }
    });
    console.log(
      "The following completing jobs are not in production, or are arriving within the next 180 days. ",
      issues
    );

    setLoading(false);
  };

  if (currentUser.email === "patrick@imex.prod")
    return (
      <Button loading={loading} onClick={handleVerify}>
        Developer Use Only - Verify Schedule Integrity
      </Button>
    );
  else return null;
}
