import React from "react";
import {
  View,
  Text,
  ActivityIndicator,
  ListView,
  RefreshControl,
} from "react-native";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useQuery } from "@apollo/client";
import { QUERY_ALL_ACTIVE_JOBS } from "../../graphql/jobs.queries";
import styles from "../styles";
import {
  Container,
  Content,
  Card,
  CardItem,
  Icon,
  Right,
  H1,
} from "native-base";
import { FlatList } from "react-native-gesture-handler";
import ErrorDisplay from "../error-display/error-display.component";
import LoadingDisplay from "../loading-display/loading-display.component";

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 () => {
    await 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={renderItem}
    />
  );
}
const renderItem = ({ item }) => {
  return (
    <CardItem>
      <View>
        <H1>{`${item.est_number}${
          item.ro_number ? ` ${item.ro_number}` : ""
        }`}</H1>
        <Text>{`${item.ownr_fn || ""} ${item.ownr_ln || ""} ${
          item.ownr_co_nm || ""
        }`}</Text>
        <Text>{`${item.v_model_yr || ""} ${item.v_make_desc || ""} ${
          item.v_model_desc || ""
        }`}</Text>
      </View>
      <Right>
        <Text>{item.ded_amt}</Text>
      </Right>
      <Right>
        <Icon name="arrow-forward" />
      </Right>
    </CardItem>
  );
};

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