// 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 { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibTheme } from 'esoftplay/cache/lib/theme/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 { MarketProduct_discuss_product_item } from 'esoftplay/cache/market/product_discuss_product_item/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

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


export interface MarketProduct_discuss_product_listArgs {

}
export interface MarketProduct_discuss_product_listProps {

}
export default function m(props: MarketProduct_discuss_product_listProps): any {
  const { merchant_id } = LibNavigation.getArgsAll<any>(props)
  const inputRef = useRef<LibInput>(null)
  let keyword = useRef<string>('').current
  const [query, setQuery] = useSafeState('')

  const [upData, setUpData] = useSafeState<any>()

  let url = 'shop/product_list?merchant_id=' + merchant_id

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

  function selectProduct(index: any, checked: 1 | 0) {
    setUpData((t) => LibObject.set(t, checked)(index, 'checked'))
  }

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

  function renderError(error: any) {
    return (
      <MarketEmpty msg={error} />
    )
  }

  function renderItems(item: any, i: number) {
    return (
      <MarketProduct_discuss_product_item key={i} {...item} onPress={() => {
        if (upData?.filter((item: any) => item.checked == 1).length == 3) {
          if (item.checked == 1) {
            selectProduct(i, item.checked == 1 ? 0 : 1)
          } else {
            LibToastProperty.show(esp.lang("market/product_discuss_product_list", "max_product"))
          }
        } else {
          selectProduct(i, item.checked == 1 ? 0 : 1)
        }
      }} selected={item.checked == 1} />
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: "#fff" }}>
      <MarketHeader onlyBack title={esp.lang("market/product_discuss_product_list", "header")} style={{ backgroundColor: '#fff' }} />

      <View style={styleId_gH0oe} >
        <View style={styleId_1O3Ixd} >
          <LibIcon name="magnify" color={LibTheme._colorTextTertiary()} style={styleId_1hcIwd} />
          <LibInput
            ref={inputRef}
            placeholder={esp.lang("market/ads_product_list", "search_product")}
            onChangeText={(t) => { keyword = t }}
            onSubmitEditing={() => {
              setQuery(keyword)
            }}
            base={true}
            style={styleId_Z2bQ6be} />
          {
            query != '' &&
            <TouchableOpacity onPress={() => {
              setQuery('')
              inputRef?.current?.setText('')
            }} >
              <LibIcon name="close" color={LibTheme._colorTextTertiary()} />
            </TouchableOpacity>
          }
        </View>
      </View>

      <LibInfinite
        key={buildUrl(url)}
        url={buildUrl(url)}
        onDataChange={(dt: any, page: number) => {
          const newData = dt.length > 0 && dt.map((item: any, i: number) => {
            return ({
              ...item,
              // checked: item.promo_req_id > 0 ? 1 : 0
              checked: 0
            })
          })
          setUpData(newData)
        }}
        injectData={upData}
        // isDebug={1}
        errorView={renderError}
        renderItem={renderItems}
      />

      <View pointerEvents={'auto'} style={styleId_Z1xBC1A}>
        <Text allowFontScaling={false} style={styleId_Ze5ku0} >{esp.lang("market/product_discuss_product_list", "total", upData?.filter((item: any) => item.checked == 1).length)}</Text>
        <MarketButton
          colorBackground={upData?.filter((item: any) => item.checked == 1).length > 0 ? MarketStyle.colorPrimaryMarket : "#aaa"}
          onPress={() => {
            LibNavigation.sendBackResult(upData?.filter((item: any) => item.checked == 1))
          }} text={esp.lang("market/ads_product_list", "btn_select")} />
      </View>

    </View>
  )
}

const styleId_1hcIwd: any = { marginRight: 10 }
const styleId_gH0oe: any = { paddingHorizontal: 17, marginTop: 15, marginBottom: 8 }
const styleId_1O3Ixd: any = { flexDirection: "row", alignItems: "center", borderWidth: 1, borderRadius: 20, borderColor: "#ddd", backgroundColor: "#f1f1f1", paddingHorizontal: 10 }
const styleId_Z2bQ6be: any = { flex: 1, paddingVertical: Platform.OS == 'ios' ? 10 : 4, fontSize: 14 }
const styleId_Z1xBC1A: any = { padding: 20, paddingVertical: 10, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }
const styleId_Ze5ku0: any = { fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0 }