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 { openImagePicker } from "@/redux/photos/photos.actions";
import JobListItem from "./job-list-item";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  openImagePicker: (id) => dispatch(openImagePicker(id)),
});

export function JobListComponent({ bodyshop, openImagePicker }) {
  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();
  };

  const handleTempUpload = () => {
    openImagePicker(); //Kept null for temp docs.
  };

  if (loading) return <ActivityIndicator style={{ flex: 1 }} />;
  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 }} edges={["top"]}>
      <View
        style={{
          display: "flex",
          flexDirection: "row",
          alignContent: "space-between",
          alignItems: "center",
        }}
      >
        <Text
          variant="headlineMedium"
          style={{ marginBottom: 12, fontWeight: "600", flex: 1 }}
        >
          {t("joblist.titles.jobtab")}
        </Text>
        <Button
          icon="cloud-upload-outline"
          mode="outlined"
          onPress={handleTempUpload}
        >
          {t("joblist.labels.tempdocs")}
        </Button>
      </View>
      <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, mapDispatchToProps)(JobListComponent);
