import { useLazyQuery } from "@apollo/client";
import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import _ from "lodash";

import {
  SEARCH_JOBS_BY_ID_FOR_AUTOCOMPLETE,
  SEARCH_JOBS_FOR_AUTOCOMPLETE,
} from "../../graphql/jobs.queries";
import { StyleSheet, Text, View } from "react-native";
import { Dropdown } from "react-native-element-dropdown";
import { connect } from "react-redux";
import { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";

export function JobIdSearchSelect(
  props
  //   //currentValue,
  //   ...restProps
) {
//   console.log("JobIdSearchSelectprops:", props);
  const notExported =
    props.notExported !== undefined ? props.notExported : true;
  const notInvoiced =
    props.notInvoiced !== undefined ? props.notInvoiced : false;
  const convertedOnly =
    props.convertedOnly !== undefined ? props.convertedOnly : false;
  const clm_no = props.clm_no !== undefined ? props.clm_no : false;

//   console.log("notExported:", notExported);
//   console.log("notInvoiced:", notInvoiced);
//   console.log("convertedOnly:", convertedOnly);
//   console.log("clm_no:", clm_no);
  const { t } = useTranslation();
  const [theOptions, setTheOptions] = useState([]);

  const [selectorData, setSelectorData] = useState([]);
  const [selectedvalue, setSelectedValue] = useState(null);
  const [isFocus, setIsFocus] = useState(false);

  const [callIdSearch, { loading: idLoading, error: idError, data: idData }] =
    useLazyQuery(SEARCH_JOBS_BY_ID_FOR_AUTOCOMPLETE);

  const [callSearch, { loading, error, data }] = useLazyQuery(
    SEARCH_JOBS_FOR_AUTOCOMPLETE,
    {}
  );
  const executeSearch = (v) => {
    // console.log("executeSearchWithV:", v);
    if (v && v !== "") callSearch(v);
  };
  const debouncedExecuteSearch = _.debounce(executeSearch, 500);

  const handleSearch = (value) => {
    // console.log("handleSearchWithValue:", value);
    debouncedExecuteSearch({
      variables: {
        search: value,
        ...(convertedOnly || notExported
          ? {
              ...(convertedOnly ? { isConverted: true } : {}),
              ...(notExported ? { notExported: true } : {}),
              ...(notInvoiced ? { notInvoiced: true } : {}),
            }
          : {}),
      },
    });
  };

  //   useEffect(() => {
  //     console.log("useEfectDependentOn: restProps.value, callIdSearch", restProps);
  //     if (restProps.value) {
  //         console.log("restPropsValue:", restProps.value);
  //       callIdSearch({ variables: { id: restProps.value } });
  //     }
  //   }, [restProps.value, callIdSearch]);

  useEffect(() => {
    // console.log("useEfectDependentOn: [data, idData]");

    // console.log( "idDataValue:", idData && idData.jobs_by_pk ? [idData.jobs_by_pk] : []);
    // console.log("dataValue:", data && data.search_jobs ? data.search_jobs : []);

    if (data) {
      setTheOptions(
        _.uniqBy(
          [
            ...(idData && idData.jobs_by_pk ? [idData.jobs_by_pk] : []),
            ...(data && data.search_jobs ? data.search_jobs : []),
          ],
          "id"
        )
      );
    }
  }, [data, idData]);

  useEffect(() => {
    if (typeof theOptions !== "undefined") {
      //  console.log("useEfectDependentOn: [theOptions]");
      var count = Object.keys(theOptions).length;
      // console.log("useEfectDependentOn: [theOptions] count:", count);
      let selectDataArray = [];
      for (let i = 0; i < count; i++) {
        selectDataArray.push({
          value: theOptions[i].id,
          label: `${
            clm_no && theOptions[i].clm_no ? `${theOptions[i].clm_no} | ` : ""
          }${
            theOptions[i].ro_number || t("general.labels.na")
          } | ${OwnerNameDisplayFunction(theOptions[i])} | ${
            theOptions[i].v_model_yr || ""
          } ${theOptions[i].v_make_desc || ""} ${
            theOptions[i].v_model_desc || ""
          }`,
        });
      }
      setSelectorData(selectDataArray);
    }
  }, [theOptions]);

  //   useEffect(() => {
  //     console.log("useEffectonselectedvaluechange:", selectedvalue.value);
  //     if (typeof onJobSelected !== "undefined") {
  //         console.log("onJobSelected:", selectedvalue.value);
  //         onJobSelected(selectedvalue.value);
  //     }
  //   }, [selectedvalue]);

  return (
    <View style={styles.container}>
      <Dropdown
        style={[styles.dropdown, isFocus && { borderColor: "blue" }]}
        placeholderStyle={styles.placeholderStyle}
        selectedTextStyle={styles.selectedTextStyle}
        inputSearchStyle={styles.inputSearchStyle}
        iconStyle={styles.iconStyle}
        search
        maxHeight={200}
        labelField="label"
        valueField="value"
        placeholder={!isFocus ? t("selectjobid.labels.placeholder") : t("selectjobid.labels.selectedplaceholder")}
        searchPlaceholder={t("selectjobid.labels.searchplaceholder")}
        onFocus={() => setIsFocus(true)}
        onBlur={() => setIsFocus(false)}
        data={selectorData}
        value={props.currentValue?.value} //{selectedvalue}
        onChange={(item) => {
          // console.log("onChange Fired!!!!");
          props.onJobSelected(item);
          setIsFocus(false);
        }} 
        
        
        //TODO: add setIsFocus(false); to this
        //     {
        //     console.log("onValueSelected!!!!");
        //    // (item) => {onJobSelected(item.value)};
        //     console.log("onChangefired!!!!");
        //     console.log("itemSelected", item);
        //     onJobSelected(item.value);
        //     setSelectedValue(item.value);

        // console.log("onValueSelected",onValueSelected);
        // if (onValueSelected){
        //     console.log("onValueSelected!!!!");
        // }

        //console.log(item);
        //   setSelectedValue(item.value);
        // if (onValueSelected) onValueSelected(item.value);

        //   setIsFocus(false);
        // }}
        onChangeText={(search) => {
          if (search && search !== "") {
            // console.log("onChangeTextFired!!!!");
            handleSearch(search);
          }
        }}
      />
      {/* {theOptions ? console.log(theOptions): null} */}
    </View>
  );
}

export default connect(null, null)(JobIdSearchSelect);

const styles = StyleSheet.create({
  container: {
    marginVertical: 4,
    marginHorizontal: 16,
    justifyContent: "center",
    alignContent: "center",
  },
  dropdown: {
    height: 50,
    borderColor: "gray",
    borderWidth: 0.5,
    borderRadius: 4,
    paddingHorizontal: 8,
  },
  icon: {
    marginRight: 5,
  },
  label: {
    position: "absolute",
    backgroundColor: "white",
    left: 22,
    top: 8,
    zIndex: 999,
    paddingHorizontal: 8,
    fontSize: 14,
  },
  placeholderStyle: {
    fontSize: 14,
  },
  selectedTextStyle: {
    fontSize: 14,
  },
  iconStyle: {
    width: 20,
    height: 20,
  },
  inputSearchStyle: {
    height: 40,
    fontSize: 14,
  },
});
