import React, { useEffect, useMemo } from "react";
import { useQuery, useSubscription } from "@apollo/client";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_JOBS_IN_PRODUCTION, SUBSCRIPTION_JOBS_IN_PRODUCTION } from "../../graphql/jobs.queries";
import { QUERY_KANBAN_SETTINGS } from "../../graphql/user.queries";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import ProductionBoardKanbanComponent from "./production-board-kanban.component";

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

function ProductionBoardKanbanContainer({ bodyshop, currentUser }) {
  const combinedStatuses = useMemo(
    () => [
      ...bodyshop.md_ro_statuses.production_statuses,
      ...(bodyshop.md_ro_statuses.additional_board_statuses || [])
    ],
    [bodyshop.md_ro_statuses.production_statuses, bodyshop.md_ro_statuses.additional_board_statuses]
  );

  const { refetch, loading, data } = useQuery(QUERY_JOBS_IN_PRODUCTION, {
    pollInterval: 3600000,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    onError: (error) => console.error(`Error fetching jobs in production: ${error.message}`)
  });

  const { data: updatedJobs } = useSubscription(SUBSCRIPTION_JOBS_IN_PRODUCTION, {
    onError: (error) => console.error(`Error subscribing to jobs in production: ${error.message}`)
  });

  const { loading: associationSettingsLoading, data: associationSettings } = useQuery(QUERY_KANBAN_SETTINGS, {
    variables: { email: currentUser.email },
    onError: (error) => console.error(`Error fetching Kanban settings: ${error.message}`)
  });

  // const currentReducerData = useSelector((state) => (state.trello.lanes ? state.trello : {}));

  useEffect(() => {
    if (updatedJobs && data) {
      refetch().catch((err) => console.error(`Error re-fetching jobs in production: ${err.message}`));
    }
  }, [updatedJobs, data, refetch]);

  const filteredAssociationSettings = useMemo(() => {
    return associationSettings?.associations[0] || null;
  }, [associationSettings]);

  return (
    <ProductionBoardKanbanComponent
      loading={loading || associationSettingsLoading}
      data={data ? data.jobs : []}
      refetch={refetch}
      associationSettings={filteredAssociationSettings}
      bodyshop={bodyshop}
      statuses={combinedStatuses}
    />
  );
}

export default connect(mapStateToProps)(ProductionBoardKanbanContainer);
