// withHooks
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';


import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInfinite } from 'esoftplay/cache/lib/infinite/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketMerchant_voucher_inputProperty } from 'esoftplay/cache/market/merchant_voucher_input/import';
import { MarketMerchant_voucher_product_item } from 'esoftplay/cache/market/merchant_voucher_product_item/import';
import { UserClass } from 'esoftplay/cache/user/class/import';

import React, { useEffect, useRef } from 'react';
import { Keyboard, Text, TextInput, TouchableOpacity, View } from 'react-native';


export interface MarketMerchant_voucher_product_listArgs {

}
export interface MarketMerchant_voucher_product_listProps {

}
export default function m(props: MarketMerchant_voucher_product_listProps): any {
  let inputText = useRef<TextInput>(null)
  let keyword = useRef<string>('').current
  const user = UserClass.state().get()
  const [selectedProduct, setSelectedProduct] = MarketMerchant_voucher_inputProperty.state().useState()

  const [query, setQuery] = useSafeState('')

  let url = "shop/merchant_product?merchant_id=" + user?.merchant_id

  useEffect(() => {
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  function buildUrl(url: string): string {
    if (query != '') {
      url += url.includes('?') ? '&' : '?'
      url += 'keyword=' + query
    }
    return url
  }

  function selectProducts(item: any, id: string) {
    let _item = [...MarketMerchant_voucher_inputProperty.state().get()]
    let index = _item.map((x: any) => x.id).indexOf(id)

    if (_item.some((x: any) => id == x.id)) {
      _item = LibObject.splice(_item, index, 1)()
    } else {
      _item = LibObject.push(_item, item)()
    }
    MarketMerchant_voucher_inputProperty.state().set([..._item])
  }

  function renderItems(item: any, i: number) {
    return (
      <MarketMerchant_voucher_product_item {...item} onPress={() => {
        selectProducts(item, item.id)
      }} selected={selectedProduct.some((x: any) => x.id == item.id || item.id == x.product_id)} />
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <MarketHeader onlyBack title={esp.lang("market/merchant_voucher_product_list", "header_title")} subtitle={esp.lang("market/merchant_voucher_product_list", "header_sub")} />
      <View style={{ marginBottom: 10, marginTop: 10, marginHorizontal: 17, flexDirection: 'row', alignItems: 'center', height: 35, borderRadius: 17.5, backgroundColor: "#f5f5f5" }} >
        <LibPicture style={{ height: 15, width: 15, marginLeft: 6, marginRight: 6 }} source={esp.assets('market/ic_search.png')} />
        <TextInput
          ref={inputText}
          style={{ fontFamily: "ArialBold", fontSize: 14, color: "#9e9e9e", flex: 1 }}
          placeholder={esp.lang("market/merchant_voucher_product_list", "search")}
          onChangeText={(t) => { keyword = t }}
          returnKeyType={'search'}
          returnKeyLabel={'Search'}
          placeholderTextColor={'#e5e5e5'}
          onSubmitEditing={() => {
            setQuery(keyword)
          }}
        />
        {
          query != '' &&
          <TouchableOpacity activeOpacity={1} onPress={() => {
            setQuery('')
            inputText.current?.setNativeProps({ text: '' })
            Keyboard.dismiss()
          }} style={{ marginRight: 10 }} >
            <LibIcon name="close" color="#e6e6e6" />
          </TouchableOpacity>
        }
      </View>

      <LibInfinite
        key={query}
        url={buildUrl(url)}
        style={{ marginHorizontal: 5 }}
        errorView={(e: string) => (<MarketEmpty msg={e} />)}
        renderItem={renderItems}
      />
      <View style={{ padding: 10, backgroundColor: '#fff' }}>
        {
          selectedProduct.length > 0 &&
          <Text allowFontScaling={false} style={{ marginVertical: 5, fontSize: 14, fontStyle: "normal", letterSpacing: 0 }} >{esp.lang("market/merchant_voucher_product_list", "selected_product", String(selectedProduct?.length))}</Text>
        }

        <MarketButton onPress={() => {
          if (selectedProduct.length > 0) {
            LibNavigation.sendBackResult(selectedProduct, 92)
          } else {
            LibToastProperty.show(esp.lang("market/merchant_voucher_product_list", "empty_product"))
          }
        }} text={esp.lang("market/merchant_voucher_product_list", "btn_save")} />
      </View>

    </View>
  )
}