import { useQuery } from "@apollo/client/react";
import { Card, Col, Row, Space } from "antd";
import dayjs from "../../utils/day";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useSearchParams } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import TimeTicketsDatesSelector from "../../components/ticket-tickets-dates-selector/time-tickets-dates-selector.component";
import TimeTicketList from "../../components/time-ticket-list/time-ticket-list.component";
import TimeTicketsPayrollTable from "../../components/time-tickets-payroll-table/time-tickets-payroll-table.component";
import TimeTicketsSummaryEmployees from "../../components/time-tickets-summary-employees/time-tickets-summary-employees.component";
import { QUERY_TIME_TICKETS_IN_RANGE } from "../../graphql/timetickets.queries";
import TimeTicketsAttendanceTable from "../../components/time-tickets-attendance-table/time-tickets-attendance-table.component";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import TimeTicketsCommit from "../../components/time-tickets-commit/time-tickets-commit.component";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { selectBodyshop } from "../../redux/user/user.selectors";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function TimeTicketsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
  const {
    treatments: { Enhanced_Payroll }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });
  const { t } = useTranslation();
  const [searchParams] = useSearchParams();
  const { start, end } = Object.fromEntries(searchParams);

  const startDate = start ? dayjs(start) : dayjs().startOf("week").subtract(7, "day");
  const endDate = end ? dayjs(end) : dayjs().endOf("week");

  const { loading, error, data } = useQuery(QUERY_TIME_TICKETS_IN_RANGE, {
    variables: {
      start: startDate,
      end: endDate
    },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    document.title = t("titles.timetickets", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
    setSelectedHeader("timetickets");
    setBreadcrumbs([
      {
        link: "/manage/timetickets",
        label: t("titles.bc.timetickets")
      }
    ]);
  }, [t, setBreadcrumbs, setSelectedHeader]);

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

  return (
    <FeatureWrapperComponent
      featureName="timetickets"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().timetickets.general} />
        </Card>
      }
    >
      <RbacWrapper action="timetickets:list">
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <TimeTicketList
              loading={loading}
              timetickets={data ? data.timetickets : []}
              extra={
                <Space wrap>
                  <TimeTicketsAttendanceTable />
                  <TimeTicketsPayrollTable />
                  {Enhanced_Payroll.treatment === "on" && (
                    <TimeTicketsCommit timetickets={data ? data.timetickets : []} />
                  )}
                  <TimeTicketsDatesSelector />
                </Space>
              }
            />
          </Col>
          <Col span={24}>
            <TimeTicketsSummaryEmployees
              loading={loading}
              timetickets={data ? data.timetickets : []}
              startDate={startDate}
              endDate={endDate}
            />
          </Col>
        </Row>
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

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