import { Form } from "antd";
import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { connect } from "react-redux";
import { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { QUERY_TEAMS } from "../../graphql/employee_teams.queries";
import useConfirmDirtyFormNavigation from "../../hooks/useConfirmDirtyFormNavigation.jsx";
import AlertComponent from "../alert/alert.component";
import RbacWrapper from "../rbac-wrapper/rbac-wrapper.component";
import ShopEmployeeTeamsListComponent from "./shop-employee-teams.list";
import ShopEmployeeTeamsFormComponent from "./shop-employee-teams.form.component";
import "./shop-teams.styles.scss";

const mapStateToProps = createStructuredSelector({});

function ShopTeamsContainer() {
  const [form] = Form.useForm();
  const [isTeamFormDirty, setIsTeamFormDirty] = useState(false);
  const navigate = useNavigate();
  const search = queryString.parse(useLocation().search);
  const { loading, error, data } = useQuery(QUERY_TEAMS, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });
  const hasSelectedTeam = Boolean(search.employeeTeamId);
  const hasDirtyTeamForm = Boolean(search.employeeTeamId) && isTeamFormDirty;
  const confirmCloseDirtyTeam = useConfirmDirtyFormNavigation(hasDirtyTeamForm);

  const navigateToTeam = (employeeTeamId) => {
    if (employeeTeamId === search.employeeTeamId) return;
    if (!confirmCloseDirtyTeam()) return;

    setIsTeamFormDirty(false);
    navigate({
      search: queryString.stringify({
        ...search,
        employeeTeamId
      })
    });
  };

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

  return (
    <RbacWrapper action="employee_teams:page">
      <div
        className={["shop-teams-layout", hasSelectedTeam ? "shop-teams-layout--with-detail" : null]
          .filter(Boolean)
          .join(" ")}
      >
        <div className="shop-teams-layout__list">
          <ShopEmployeeTeamsListComponent
            employee_teams={data ? data.employee_teams : []}
            loading={loading}
            onRequestTeamChange={navigateToTeam}
            selectedTeamId={search.employeeTeamId}
          />
        </div>
        {hasSelectedTeam ? (
          <div className="shop-teams-layout__details">
            <ShopEmployeeTeamsFormComponent form={form} onDirtyChange={setIsTeamFormDirty} isDirty={isTeamFormDirty} />
          </div>
        ) : null}
      </div>
    </RbacWrapper>
  );
}

export default connect(mapStateToProps, null)(ShopTeamsContainer);
