// 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 { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/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_itemProps } from 'esoftplay/cache/market/product_item/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { UserClass } from 'esoftplay/cache/user/class/import';

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


export interface MarketMerchant_product_listProps {

}

export default function m(props: MarketMerchant_product_listProps): any {
  const { def_product_ids, url } = LibNavigation.getArgsAll<any>(props)
  const user = UserClass.state().useSelector(s => s)
  const [product_ids, setProduct_ids, getProduct_ids] = useSafeState<string[]>([])
  const [query, setQuery] = useSafeState("")
  let pendingQuery = useRef<string>("").current
  let _url = "shop/product_list?merchant_id=" + user?.merchant_id + "&keyword=" + query
  if (url) {
    _url = url
    _url += _url.includes("?") ? "&" : "?"
    _url += "keyword=" + query
  }

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

  function toggle(id: string) {
    if (getProduct_ids().includes(id))
      setProduct_ids((d: any) => d.filter((x) => x != id))
    else
      setProduct_ids((t) => [...t, id])
  }

  function renderItem(item: MarketProduct_itemProps, index: number) {
    const active = product_ids.includes(String(item.id))
    const disabled = item?.is_labeled == 1
    return (
      <TouchableOpacity
        disabled={disabled}
        onPress={() => toggle(item.id)}
        style={{ opacity: disabled ? 0.2 : 1, paddingHorizontal: 17, flexDirection: 'row', alignItems: 'flex-start', marginBottom: 5, backgroundColor: "white", paddingVertical: 10 }} >
        <LibIcon name={active || disabled ? "checkbox-marked-outline" : "checkbox-blank-outline"} size={22} color={MarketStyle.colorGreen} />
        <LibPicture source={{ uri: item.image }} style={{ height: 55, width: 55, borderRadius: 5, backgroundColor: "#f1f2f3", marginHorizontal: 10, }} />
        <View style={{ flex: 1, alignItems: 'center', flexDirection: "row", paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: "#f9f9f9" }} >
          <View style={{ flex: 1, justifyContent: "space-around" }} >
            <LibTextstyle text={item.title} textStyle="caption2" style={{ color: "#888" }} />
            <LibTextstyle text={LibUtils.money(item.price)} textStyle="footnote" />
          </View>
          {/* <View> */}
          {/* <LibTextstyle text={LibUtils.money(item.sale)} textStyle="caption2" style={{ color: "#888", textDecorationLine: 'line-through', textDecorationStyle: 'solid' }} /> */}
          {/* <LibTextstyle text={LibUtils.money(item.price)} textStyle="caption1" style={{ color: "#888" }} /> */}
          {/* </View> */}
        </View>
      </TouchableOpacity>
    )
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader
        onlyBack
        centerView={() => (
          <View style={{ flex: 1, backgroundColor: "#f1f2f3", borderRadius: 10, height: 36, paddingHorizontal: 12, flexDirection: 'row', alignItems: 'center' }} >
            <LibInput
              base
              placeholder={esp.lang("market/merchant_product_list", "search")}
              style={{ flex: 1 }}
              onSubmitEditing={() => {
                Keyboard.dismiss()
                setQuery(pendingQuery)
              }}
              onChangeText={t => pendingQuery = t} />
            {
              query.length > 0 &&
              <TouchableOpacity onPress={() => { setQuery("") }} >
                <LibIcon name="close-circle" size={16} color={'#aaa'} />
              </TouchableOpacity>
            }
          </View>
        )}
        rightView={() => (
          <TouchableOpacity
            onPress={() => {
              Keyboard.dismiss()
              setQuery(pendingQuery)
            }}
            style={{ width: 50, alignItems: 'center' }} >
            <LibIcon name={"magnify"} />
          </TouchableOpacity>
        )} />
      <LibInfinite
        key={query}
        url={_url}
        onDataChange={esp.log}
        renderItem={renderItem}
        errorView={(e: string) => (<MarketEmpty msg={e} />)}
      />
      <View style={{ paddingVertical: 10, backgroundColor: "#f9f9f9", ...LibStyle.elevation(2) }} >
        <LibTextstyle textStyle="callout" text={esp.lang("market/merchant_product_list", "selected_product", String(product_ids?.length))} style={{ textAlign: 'center', marginBottom: 10, color: "#888" }} />
        <MarketButton
          buttonStyle={{ marginHorizontal: 17, marginVertical: 10 }}
          text={esp.lang("market/merchant_product_list", "btn_save")} onPress={() => LibNavigation.sendBackResult(product_ids, LibNavigation.getResultKey(props))} />
      </View>
    </View>
  )
}