// 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 { LibStyle } from 'esoftplay/cache/lib/style/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 { MarketPromotion_product_item } from 'esoftplay/cache/market/promotion_product_item/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

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


interface Promo {
  discount_max: string,
  discount_min: string,
  end_datetime: string,
  id: string,
  merchant_product: number,
  price_max: string,
  price_min: string,
  product_cat: string,
  product_list: string,
  start_datetime: string,
  title: string,
}
export interface MarketPromotion_productArgs {
  promo: Promo
  product_id: any[],
  promo_id?: string,
  product_cat_id?: string
}
export interface MarketPromotion_productProps {

}

export default function m(props: MarketPromotion_productProps): any {
  const { promo, product_id, promo_id, product_cat_id } = LibNavigation.getArgsAll<MarketPromotion_productArgs>(props)
  let query = useRef<string>('').current
  const [querySubmitted, setQuerySubmitted] = useSafeState('')
  const [upData, setUpData, getUpData] = useSafeState<any>()
  let url = promo.product_list

  let lengthAvail: boolean = (upData?.filter?.((x: any) => x.checked == 1).length || 0) < promo.merchant_product

  function selectProduct(id: string, index: any, checked: 1 | 0) {
    const includesId: boolean = getUpData().filter((x: any) => x.checked == 1).map((x: any) => x.id).includes(id)

    if (includesId) {
      setUpData((t) => LibObject.set(t, 0)(index, 'checked'))
    } else if (lengthAvail) {
      setUpData((t) => LibObject.set(t, checked)(index, 'checked'))
    } else {
      let a = (getUpData()?.filter?.((x: any) => x.checked == 1).length || 0)
      LibToastProperty.show(esp.lang("market/promotion_product", "max_quota", a, String(promo.merchant_product)))
    }
  }

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

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

  function renderItems(item: any, i: number) {
    return (
      <MarketPromotion_product_item {...item} onSelected={() => { selectProduct(item.id, i, item.checked == 0 ? 1 : 0) }} available={!upData?.filter?.((x: any) => x.checked == 1).map((x: any) => x.id).includes(item.id) && !lengthAvail} />
    )
  }

  let enabled = (upData?.filter?.((x: any) => x.checked == 1).length || 0) > 0

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader title={esp.lang("market/promotion_product", "header_title")} onlyBack />
      <View style={{ marginBottom: 10, marginTop: 10, marginHorizontal: 17, flexDirection: 'row', alignItems: 'center', height: 35, borderRadius: 17, backgroundColor: "#f5f5f5" }} >
        <LibPicture style={{ height: 15, width: 15, marginLeft: 10, marginRight: 6 }} source={esp.assets('market/ic_search.png')} />
        <TextInput
          style={{ fontFamily: "ArialBold", fontSize: 12, color: "#9e9e9e", flex: 1 }}
          placeholder={esp.lang("market/promotion_product", "search")}
          onChangeText={(t) => { query = t }}
          returnKeyType={'search'}
          returnKeyLabel={'Search'}
          placeholderTextColor={'#e5e5e5'}
          onSubmitEditing={() => {
            Keyboard.dismiss()
            setQuerySubmitted(query)
          }}
        />
        {
          querySubmitted != '' &&
          <TouchableOpacity activeOpacity={1} onPress={() => { setQuerySubmitted('') }} style={{ marginRight: 10 }} >
            <LibIcon name="close" color="#e6e6e6" />
          </TouchableOpacity>
        }
      </View>
      <LibInfinite
        url={buildUrl(url)}
        key={buildUrl(url)}
        isDebug={1}
        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: product_id?.includes(item.id) ? 1 : 0
            })
          })
          setUpData(newData)
        }}
        injectData={upData}
        style={{ marginTop: 10 }}
        errorView={(x: string) => (
          <>
            <MarketEmpty msg={x} />
            <MarketButton
              onPress={() => { LibNavigation.navigate('market/product_add') }}
              text={esp.lang("market/promotion_product", "add_new")}
              textStyle={{ color: 'white', fontSize: 12, }}
              colorBackground={MarketStyle.colorPrimaryMarket}
              buttonStyle={{ margin: 10, borderRadius: 20, width: 150, alignSelf: 'center' }}
            />
          </>
        )}
        renderItem={renderItems}
      />
      {/* {
        promo.merchant_product > 0 &&
        <View style={{ marginHorizontal: 17, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }} >
          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "normal", fontStyle: "normal", lineHeight: 17, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{'Limit produk untuk program promosi'}</Text>
          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", lineHeight: 17, letterSpacing: 0, textAlign: "right", color: "#03192a" }} >({(upData?.filter?.((x: any) => x.checked == 1).length || 0) + '/' + promo.merchant_product})</Text>
        </View>
      } */}
      <MarketButton
        text={esp.lang("market/promotion_product", "btn_add")}
        textStyle={{ color: enabled ? 'white' : '#000' }}
        colorBackground={enabled ? MarketStyle.colorPrimaryMarket : LibStyle.colorGrey}
        buttonStyle={{ marginHorizontal: 15, marginVertical: 10, borderRadius: 20 }}
        onPress={() => {
          if (enabled) {
            // LibNavigation.navigate<MarketPromotion_product_selectedArgs>('market/promotion_product_selected', { products: upData.filter((x: any) => x.checked == 1), promo: promo, promo_id: promo_id, product_cat_id: product_cat_id })
            LibNavigation.sendBackResult(upData.filter((x: any) => x.checked == 1), LibNavigation.getResultKey(props))
          }
        }}
      />
    </View>
  )
}