import { FlatList, RefreshControl, StyleSheet, Text, View } from "react-native";
import React from "react";
import { Ionicons } from "@expo/vector-icons";
import { Button, List, Searchbar } from "react-native-paper";
import { useState } from "react";
import { SEARCH_JOBS_FOR_AUTOCOMPLETE } from "../../graphql/jobs.queries";
import { useQuery } from "@apollo/client";

function JobIdSearchAndList({ onClose }) {
  const jobSrchNotExported = true;
  const jobSrchNotInvoiced = false;
  const jobSrchConvertedOnly = false;

  const jobSrchCurrentValue = { id: "temp", ro_number: "Temporary Storage" };
  const jobSrchOnSetCurrentValue = (e) => {
    console.info("onSetCurrentValue was called", e);
  };
  const jobSrchCurrentValueId = "temp";
  const jobSrchOnSetCurrentValueId = () => {
    console.info("onSetCurrentValueId was called");
  };

  const [searchText, setSearchText] = useState(null);
  const [loading2, setLoading2] = useState(null);

  console.log("onClose :", onClose);
  // const showModal = () => setVisible(true);
  const close = onClose ? onClose : () => console.info("todo add close"); //setVisible(false);
  const onChangeSearch = (query) => {
    console.log("onChangeSearch text:", query);
    setSearchText(query);
  };
  const onRefresh = async () => {
    //7/18
    setLoading2(true);
    // refetch();
    setTimeout(() => {
      setLoading2(false);
    }, 1000);

    //7/17
    //  setRefreshing(true);
    //     console.log(" ");
    //     console.log(" ");
    //     console.log(" ");
    //     console.log(" ");
    //     console.log(" ");
    //     console.log("onRefresh was called");

    //   console.log("data:", data);
    // refetch({
    //   notInvoiced: jobSrchNotInvoiced,
    //   notExported: jobSrchNotExported,
    //   isConverted: jobSrchConvertedOnly,
    //   search: searchText,
    // });
  };

  const { loading, error, data, refetch } = useQuery(
    SEARCH_JOBS_FOR_AUTOCOMPLETE,
    {
      // fetchPolicy: "cache-and-network",
      variables: {
        search: searchText,
        ...(jobSrchConvertedOnly || jobSrchNotExported
          ? {
              ...(jobSrchConvertedOnly ? { isConverted: true } : {}),
              ...(jobSrchNotExported ? { notExported: true } : {}),
              ...(jobSrchNotInvoiced ? { notInvoiced: true } : {}),
            }
          : {}),
      },
      skip: !!!searchText,
      fetchPolicy: "network-only",
      nextFetchPolicy: "network-only",
    }
  );

  return (
    <View
      style={{
        flex: 1,
      }}
    >
      <View
        style={{
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          margin: 8,
        }}
      >
        <Button onPress={() => close()}>
          <Ionicons name="ios-arrow-back" size={32} color="dodgerblue" />
        </Button>
        <Searchbar
          style={{ flex: 1 }}
          onChangeText={(text) => onChangeSearch(text)}
          value={searchText}
        />
      </View>
      <FlatList
        refreshControl={
          <RefreshControl refreshing={loading2} onRefresh={onRefresh} />
        }
        // data={[{ id: "temp", ro_number: "Temporary Storage" }, ...jobs]}
        data={data?.search_jobs}
        keyExtractor={(item) => item.id}
        renderItem={(object) => (
          <List.Item
            onPress={() => {
              //   jobSrchOnSetCurrentValue(object.item);
              //   jobSrchOnSetCurrentValueId(object.item.id);
              hideModal();
              setSearchText("");
            }}
            left={() => {
              if (object.item.id !== jobSrchCurrentValueId) return null;
              return (
                <Ionicons
                  name="ios-checkmark-circle"
                  size={24}
                  color="dodgerblue"
                  style={{ alignSelf: "center" }}
                />
              );
            }}
            titleStyle={{
              ...(object.item.id === jobSrchCurrentValueId
                ? { color: "dodgerblue" }
                : {}),
            }}
            title={`${
              object.item.ro_number ? `${object.item.ro_number} ` : ``
            }${object.item.ownr_fn || ""} ${object.item.ownr_ln || ""}${
              object.item.v_model_yr ? `- ${object.item.v_model_yr}` : ""
            }${object.item.v_make_desc ? `- ${object.item.v_make_desc}` : ""}${
              object.item.v_model_desc ? `- ${object.item.v_model_desc}` : ""
            }`}
            key={object.item.id}
          />
        )}
        ListEmptyComponent={
          <View
            style={{
              flex: 1,
              padding: 10,
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Text>No Data</Text>
          </View>
        }
      />
    </View>
  );
}

export default JobIdSearchAndList;

const styles = StyleSheet.create({});
