import { useQuery } from "@apollo/client/react";
import { Result } from "antd";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_ACTIVE_SHIFT_TIME_TICKETS } from "../../graphql/timetickets.queries";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import TimeTicketShiftActive from "../time-ticket-shift-active/time-ticket-shift-active.component";
import TimeTicketShiftFormContainer from "../time-ticket-shift-form/time-ticket-shift-form.container";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  technician: selectTechnician,
  currentUser: selectCurrentUser
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

export function TimeTicketShiftContainer({ bodyshop, technician, currentUser, isTechConsole }) {
  const { t } = useTranslation();
  const employeeId = useMemo(() => {
    const assoc = bodyshop.associations.filter((a) => a.useremail === currentUser.email)[0];

    return assoc?.user && assoc.user.employee && assoc.user.employee.id;
  }, [bodyshop, currentUser.email]);

  const { loading, error, data, refetch } = useQuery(QUERY_ACTIVE_SHIFT_TIME_TICKETS, {
    variables: {
      employeeId: isTechConsole ? technician?.id : employeeId
    },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  if (!employeeId && !technician?.id)
    return (
      <div>
        <Result
          status="500"
          title={t("timetickets.errors.noemployeeforuser")}
          subTitle={t("timetickets.errors.noemployeeforuser_sub")}
        />
      </div>
    );

  const checkIfAlreadyClocked = async () => {
    const { data } = await refetch();

    return data.timetickets.length > 0;
  };

  return (
    <div>
      {data.timetickets.length > 0 ? (
        <TimeTicketShiftActive
          timetickets={data ? data.timetickets : []}
          refetch={refetch}
          isTechConsole={isTechConsole}
        />
      ) : (
        <TimeTicketShiftFormContainer isTechConsole={isTechConsole} checkIfAlreadyClocked={checkIfAlreadyClocked} />
      )}
    </div>
  );
}

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