import { useQuery } from "@apollo/client";
import React from "react";
import { useTranslation } from "react-i18next";
import { FlatList, RefreshControl, View } from "react-native";
import { ActivityIndicator, Button, Text } from "react-native-paper";
import { SafeAreaView } from "react-native-safe-area-context";
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 UploadProgress from "../upload-progress/upload-progress";
import JobListItem from "./job-list-item";

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

export function JobListComponent({ bodyshop }) {
  const { t } = useTranslation();

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_ACTIVE_JOBS, {
    variables: {
      statuses: bodyshop?.md_ro_statuses?.active_statuses || ["Open", "Open*"],
    },
    skip: !bodyshop,
    notifyOnNetworkStatusChange: true,
  });

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

  if (loading) return <ActivityIndicator />;
  if (error) return <Text>{error.message}</Text>;
  if (data && data.jobs && data.jobs.length === 0)
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>
          <Text>{t("joblist.labels.nojobs")}</Text>
        </Text>
        <Button onPress={() => refetch()}>
          {t("joblist.actions.refresh")}
        </Button>
      </View>
    );

  const jobs = data ? [...(data?.jobs || []), { id: "footer-spacer" }] : [];

  return (
    <SafeAreaView style={{ flex: 1, marginHorizontal: 12 }}>
      <Text
        variant="headlineMedium"
        style={{ marginBottom: 12, fontWeight: "600" }}
      >
        Jobs
      </Text>
      <UploadProgress />
      <FlatList
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={onRefresh} />
        }
        style={{ flex: 1 }}
        data={jobs}
        keyExtractor={(item) => item.id?.toString()}
        renderItem={(object) => <JobListItem item={object.item} />}
      />
    </SafeAreaView>
  );
}

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