import { useQuery } from "@apollo/client";
import React from "react";
import { RefreshControl } from "react-native";
import { FlatList } from "react-native-gesture-handler";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_ALL_ACTIVE_JOBS } from "../../graphql/jobs.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import ErrorDisplay from "../error-display/error-display.component";
import LoadingDisplay from "../loading-display/loading-display.component";
import JobListItem from "../job-list-item/job-list-item.component";
import { useNavigation } from "@react-navigation/native";

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

export function JobListComponent({ bodyshop }) {
  const { loading, error, data, refetch } = useQuery(QUERY_ALL_ACTIVE_JOBS, {
    variables: {
      statuses: bodyshop.md_ro_statuses.open_statuses || ["Open", "Open*"],
    },
    skip: !bodyshop,
  });

  const onRefresh = async () => {
    return refetch();
  };

  if (loading) return <LoadingDisplay />;
  if (error) return <ErrorDisplay errorMessage={error.message} />;

  return (
    <FlatList
      refreshControl={
        <RefreshControl refreshing={loading} onRefresh={onRefresh} />
      }
      style={{ flex: 1 }}
      data={data ? data.jobs : []}
      renderItem={(object) => <JobListItem item={object.item} />}
      //ItemSeparatorComponent={FlatListItemSeparator}
    />
  );
}

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