import { useQuery } from "@apollo/client";
import React from "react";
import { useTranslation } from "react-i18next";
import { FlatList, RefreshControl, Text, View } from "react-native";
import { Button, Searchbar, Title } from "react-native-paper";
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 JobListItem from "../job-list-item/job-list-item.component";
import LoadingDisplay from "../loading-display/loading-display.component";

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

export function JobListComponent({ bodyshop }) {
  const { t } = useTranslation();
  const [searchQuery, setSearchQuery] = React.useState("");
  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 onChangeSearch = (query) => setSearchQuery(query);

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

  const jobs = data
    ? searchQuery === ""
      ? data.jobs
      : data.jobs.filter(
          (j) =>
            (j.ro_number || "")
              .toString()
              .toLowerCase()
              .includes(searchQuery.toLowerCase()) ||
            (j.ownr_co_nm || "")
              .toLowerCase()
              .includes(searchQuery.toLowerCase()) ||
            (j.ownr_fn || "")
              .toLowerCase()
              .includes(searchQuery.toLowerCase()) ||
            (j.ownr_ln || "")
              .toLowerCase()
              .includes(searchQuery.toLowerCase()) ||
            (j.v_model_desc || "")
              .toLowerCase()
              .includes(searchQuery.toLowerCase()) ||
            (j.v_make_desc || "")
              .toLowerCase()
              .includes(searchQuery.toLowerCase())
        )
    : [];

  return (
    <View style={{ flex: 1 }}>
      <Searchbar onChangeText={onChangeSearch} value={searchQuery} />
      <FlatList
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={onRefresh} />
        }
        style={{ flex: 1 }}
        data={jobs}
        renderItem={(object) => <JobListItem item={object.item} />}
      />
    </View>
  );
}

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