// 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 { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTheme } from 'esoftplay/cache/lib/theme/import';
import { MarketAds_keywordArgs } from 'esoftplay/cache/market/ads_keyword/import';
import { MarketAds_product_form } from 'esoftplay/cache/market/ads_product_group/import';
import { MarketAds_product_item } from 'esoftplay/cache/market/ads_product_item/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 { MarketSlidingupProperty } from 'esoftplay/cache/market/slidingup/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { UseForm } from 'esoftplay/cache/use/form/import';

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


export interface MarketAds_product_listArgs {
  from: string
}
export interface MarketAds_product_listProps {

}
export default function m(props: MarketAds_product_listProps): any {
  const [form, setForm] = UseForm<MarketAds_product_form>('market/ads_register')
  const { from } = LibNavigation.getArgsAll<any>(props)

  const [tab, setTab, getTab] = useSafeState<any>(0)
  const inputRef = useRef<LibInput>(null)
  let keyword = useRef<string>('').current
  const [query, setQuery, getQuery] = useSafeState('')
  const [sort, setSort, getSort] = useSafeState('latest')
  const [selectedProduct, setSelectedProduct, getSelectedProduct] = useSafeState<any>(form?.products || [])
  const [cat_ids, setcat_ids, getcat_ids] = useSafeState<any>(form?.products?.map((item: any) => item?.cat_id) || [])

  let url = 'advert/ads_product'

  let _tabs = [
    {
      id: 0,
      title: esp.lang("market/ads_product_list", "tabs_0")
    },
    {
      id: 1,
      title: esp.lang("market/ads_product_list", "tabs_1")
    },
  ]

  let filters = [
    {
      id: 1,
      title: esp.lang("market/ads_product_list", "all")
    }
  ]

  let sorts = [
    {
      id: 1,
      title: esp.lang("market/ads_product_list", "newest"),
      code: 'latest'
    },
    {
      id: 2,
      title: esp.lang("market/ads_product_list", "popular"),
      code: 'popular'
    },
    {
      id: 3,
      title: esp.lang("market/ads_product_list", "best_seller"),
      code: 'best-seller'
    },
    // {
    //   id: 3,
    //   title: 'Harga Tertinggi'
    // },
    // {
    //   id: 4,
    //   title: 'Harga Terendah'
    // },
  ]


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

  function buildUrl(url: string): string {
    if (getTab() != '') {
      url += url.includes('?') ? '&' : '?'
      url += 'is_ads=' + getTab()
    }
    if (getSort() != '') {
      url += url.includes('?') ? '&' : '?'
      url += 'sort=' + getSort()
    }
    if (getQuery() != '') {
      url += url.includes('?') ? '&' : '?'
      url += 'keyword=' + getQuery()
    }
    return url
  }

  function selectProducts(item: any, cat_id: number, id: string) {
    let _item = [...getSelectedProduct()]
    let _cat_ids = [...cat_ids]
    let index = _item.map((x: any) => x.id).indexOf(id)

    if (_item.some((x: any) => id == x.id)) {
      _item = LibObject.splice(_item, index, 1)()
      _cat_ids = LibObject.splice(_cat_ids, index, 1)()
    } else {
      _item = LibObject.push(_item, item)()
      _cat_ids = LibObject.push(_cat_ids, cat_id)()
    }
    setcat_ids([..._cat_ids])
    setSelectedProduct([..._item])

    setForm("products")([..._item])
  }

  function selectProductsEdit(item: any, cat_id: number, id: string) {
    let _item = [...getSelectedProduct()]
    let _cat_ids = [...getcat_ids()]

    let index = _item.map((x: any) => x.id || x.product_id).indexOf(id)

    let product = {
      product_id: item.id || item.product_id,
      product_cat_id: item.cat_id || item.product_cat_id,
      product_name: item.title || item.product_name,
      product_image: item.image || item.product_image
    }

    if (_item.some((x: any) => ((x.id || x.product_id) == id))) {
      _item = LibObject.splice(_item, index, 1)()
      _cat_ids = LibObject.splice(_cat_ids, index, 1)()
    } else {
      _item = LibObject.push(_item, product)()
      _cat_ids = LibObject.push(_cat_ids, cat_id)()

    }

    setcat_ids([..._cat_ids])
    setSelectedProduct([..._item])
  }

  function openFilter() {
    MarketSlidingupProperty.add(
      <View style={styleId_22MUga} >
        <View style={styleId_12lRXe} >
          <TouchableOpacity onPress={() => MarketSlidingupProperty.hide()} style={styleId_1hcIwd} >
            <LibIcon name="close" size={20} />
          </TouchableOpacity>
          <Text allowFontScaling={false} style={styleId_Z26yQmp}  >{esp.lang("market/ads_product_list", "text_title")}</Text>
        </View>
        <ScrollView>
          {
            filters?.map((item: any, i: number) => {
              return (
                <TouchableOpacity onPress={() => {
                  MarketSlidingupProperty.hide()
                }} key={i} style={styleId_26qOKw}>
                  <View>
                    <Text allowFontScaling={false} style={styleId_g3yJj} >{item.title}</Text>
                    <Text allowFontScaling={false} style={styleId_1SdHAp} >{item.date}</Text>
                  </View>
                  <TouchableOpacity onPress={() => {
                    MarketSlidingupProperty.hide()
                  }}>
                    <LibIcon color={MarketStyle.colorPrimaryMarket} name={/* periodePerformAds?.id == item.id ? "radiobox-marked" : */ "radiobox-blank"} />
                  </TouchableOpacity>
                </TouchableOpacity>
              )
            })
          }
        </ScrollView>
      </View>
    )
  }

  function openSort() {
    MarketSlidingupProperty.add(
      <View style={styleId_22MUga} >
        <View style={styleId_12lRXe} >
          <TouchableOpacity onPress={() => MarketSlidingupProperty.hide()} style={styleId_1hcIwd} >
            <LibIcon name="close" size={20} />
          </TouchableOpacity>
          <Text allowFontScaling={false} style={styleId_Z26yQmp}  >{esp.lang("market/ads_product_list", "text_sort")}</Text>
        </View>
        <ScrollView>
          {
            sorts?.map((item: any, i: number) => {
              return (
                <TouchableOpacity onPress={() => {
                  setSort(item.code)
                  MarketSlidingupProperty.hide()
                }} key={i} style={styleId_26qOKw}>
                  <Text allowFontScaling={false} style={styleId_g3yJj} >{item.title}</Text>
                  <TouchableOpacity onPress={() => {
                    setSort(item.code)
                    MarketSlidingupProperty.hide()
                  }}>
                    <LibIcon color={MarketStyle.colorPrimaryMarket} name={sort == item?.code ? "radiobox-marked" : "radiobox-blank"} />
                  </TouchableOpacity>
                </TouchableOpacity>
              )
            })
          }
        </ScrollView>
      </View>
    )
  }

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

  function renderItems(item: any, i: number) {
    return (
      <MarketAds_product_item key={i} {...item} onPress={() => {
        if (from == 'market/ads_grup_edit') {
          selectProductsEdit(item, item.cat_id, item.id || item.product_id)
        } else {
          selectProducts(item, item.cat_id, item.id)
        }
      }} selected={selectedProduct.some((x: any) => x.id == item.id || item.id == x.product_id)} />
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <MarketHeader title={esp.lang("market/ads_product_list", "header_title")} onlyBack rightView={() => (
        <View style={styleId_2nLyCQ}>
          <TouchableOpacity onPress={() => {
            openFilter()
            MarketSlidingupProperty.show()
          }}>
            <LibIcon name="filter" color={"#c5c5c5"} />
          </TouchableOpacity>
          <Text allowFontScaling={false} style={styleId_25lqmL}>|</Text>
          <TouchableOpacity onPress={() => {
            openSort()
            MarketSlidingupProperty.show()
          }} >
            <LibIcon name="sort-variant" color={"#c5c5c5"} />
          </TouchableOpacity>
        </View>
      )} />

      <View style={styleId_8tdt6} >
        {
          _tabs && _tabs.map((item: any, i: number) => {
            return (
              <TouchableOpacity key={i} onPress={() => {
                setTab(i)
              }}>
                <View style={[styleId_Z2bngyw, { width: LibStyle.width / _tabs.length }]}>
                  <Text allowFontScaling={false} style={[styleId_1EeS0i, { width: LibStyle.width / _tabs.length, fontSize: tab == i ? 13 : 12, fontWeight: tab == i ? "bold" : "normal", color: tab == i ? MarketStyle.colorPrimaryMarket : "#c5c5c5" }]}>{item.title}</Text>
                  <View style={[styleId_1d3PQt, { width: (LibStyle.width / _tabs.length) - 20, backgroundColor: tab == i ? MarketStyle.colorPrimaryMarket : "#fff" }]} />
                </View>
              </TouchableOpacity>
            )
          })
        }
      </View>

      <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)}
        errorView={renderError}
        renderItem={renderItems}
      />

      <View pointerEvents={cat_ids.length > 0 ? 'auto' : 'none'} style={styleId_Z1xBC1A}>
        <Text allowFontScaling={false} style={styleId_Ze5ku0} >{esp.lang("market/ads_product_list", "selected_product", cat_ids.length)}</Text>
        <MarketButton
          colorBackground={cat_ids.length == 0 ? "#aaa" : undefined}
          onPress={() => {
            if (from == 'market/ads_summary') {
              LibNavigation.redirect()
            } else if (from == 'market/ads_grup_edit') {
              LibNavigation.sendBackResult(selectedProduct, LibNavigation.getResultKey(props))
            } else {
              LibNavigation.navigate<MarketAds_keywordArgs>('market/ads_keyword', { cat_ids: cat_ids.join(',') })
            }
          }} text={esp.lang("market/ads_product_list", "btn_select")} />
      </View>

    </View>
  )
}
const styleId_22MUga: any = { maxHeight: LibStyle.height / 2, backgroundColor: "white", paddingVertical: 15, paddingHorizontal: 17, borderTopRightRadius: 15, borderTopLeftRadius: 15 }
const styleId_12lRXe: any = { flexDirection: "row", alignItems: "center", marginBottom: 10 }
const styleId_1hcIwd: any = { marginRight: 10 }
const styleId_Z26yQmp: any = { fontWeight: 'bold', fontSize: 16 }
const styleId_26qOKw: any = { padding: 10, borderBottomWidth: 1, borderBottomColor: '#f5f5f5', flexDirection: 'row', justifyContent: 'space-between' }
const styleId_g3yJj: any = { fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0 }
const styleId_1SdHAp: any = { marginTop: 5, fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#707070" }
const styleId_2nLyCQ: any = { flexDirection: 'row', marginRight: 20 }
const styleId_25lqmL: any = { marginHorizontal: 10, fontSize: 25, color: '#f1f1f1', marginTop: -4 }
const styleId_8tdt6: any = { height: 38, marginBottom: 2, flexDirection: 'row', backgroundColor: '#fff', ...LibStyle.elevation(2) }
const styleId_Z2bngyw: any = { height: 38, alignItems: 'center', overflow: 'visible', justifyContent: 'center', backgroundColor: '#fff' }
const styleId_1EeS0i: any = { fontFamily: "Arial", fontStyle: "normal", letterSpacing: 0, textAlign: "center", }
const styleId_1d3PQt: any = { height: 3, position: 'absolute', bottom: 0 }
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 }