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


import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibFocus } from 'esoftplay/cache/lib/focus/import';
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 { LibSkeleton } from 'esoftplay/cache/lib/skeleton/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { MarketDevice_type } from 'esoftplay/cache/market/device_type/import';
import { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketMerchant_product_item } from 'esoftplay/cache/market/merchant_product_item/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

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


export interface MarketMerchant_detail_product_listArgs {
  title?: string,
  url: string,
  tab?: number
}
export interface MarketMerchant_detail_product_listProps {

}
export default function m(props: MarketMerchant_detail_product_listProps): any {
  const { title, url, tab } = LibNavigation.getArgsAll<MarketMerchant_detail_product_listArgs>(props)
  let keyword = useRef<string>('').current
  let inputText = useRef<TextInput>(null)
  const [_url, set_url] = useSafeState(url)
  const dimension = useMemo(() => MarketDevice_type(2, 4, 5), [])
  const imgDimension = useMemo(() => (LibStyle.width - ((dimension + 1) * 10)) / dimension, [])
  const [totalItem, settotalItem] = useSafeState<number>(0)
  const [activeTab, setActiveTab] = useSafeState(tab || 1)
  const [upData, setUpData] = useSafeState<any>()
  const [counter, setCounter] = useSafeState(0)
  const [query, setQuery] = useSafeState('')
  const [sort, setSort] = useSafeState('latest')
  const slideUp = useRef<LibSlidingup>(null)

  const _sort = ['latest', 'popular', 'best-seller']
  const _sortTitle = [
    esp.lang("market/merchant_detail_product_list", "latest"),
    esp.lang("market/merchant_detail_product_list", "popular"),
    esp.lang("market/merchant_detail_product_list", "best_seller")
  ]

  const tabs = [
    {
      id: 1,
      url: 'shop/merchant_product',
      title: esp.lang("market/merchant_detail_product_list", "product_active")
    },
    {
      id: 2,
      url: 'shop/merchant_product_draft',
      title: esp.lang("market/merchant_detail_product_list", "product_draft")
    }
  ]

  useEffect(() => {
    getTotalItem()
    setUpData(undefined)
  }, [activeTab, _url, query, sort])

  function getTotalItem() {
    settotalItem(0)
    new LibCurl(buildUrl(_url), null,
      (res, msg) => {
        settotalItem(res.total || 0)
      }
    )
  }

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

  function renderItems(item: any, i: number) {
    return (
      <View key={i} >
        <MarketMerchant_product_item {...item} onDelete={() => {
          setUpData(LibObject.splice(upData, i, 1)())
          getTotalItem()
        }} />
      </View>
    )
  }

  return (
    <View style={{ flex: 1 }} >
      <LibFocus onFocus={() => setCounter(counter + 1)} />
      <MarketHeader title={esp.lang("market/merchant_detail_product_list", "header_title")} subtitle={title || esp.lang("market/merchant_detail_product_list", "header_subtitle")}
        leftIcon={{ name: "arrow-left", onPress: () => LibNavigation.back() }}
        rightView={() => (
          <TouchableOpacity onPress={() => {
            LibNavigation.navigate('market/product_add')
          }} style={{ height: 50, justifyContent: 'center', paddingRight: 17 }} >
            <LibIcon name="plus" />
          </TouchableOpacity>
        )} />

      <View style={{ 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_detail_product_list", "placeholder_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>

      <View style={{ marginHorizontal: 17, flexDirection: 'row', alignItems: 'center', marginVertical: 10, flexWrap: 'wrap' }} >
        <TouchableOpacity
          onPress={() => { slideUp.current?.show() }}
          style={{ marginRight: 10, borderRadius: 20, backgroundColor: '#fff', borderColor: '#ccc', borderWidth: 1, paddingVertical: 6, paddingHorizontal: 17, justifyContent: 'center', flexDirection: 'row', alignItems: 'center' }} >
          <LibIcon name='tune' size={16} color={'#4E4E4E'} style={{ marginRight: 5 }} />
          <LibTextstyle textStyle='footnote' text={esp.lang("market/merchant_detail_product_list", "sort")} style={{ color: '#4E4E4E' }} />
        </TouchableOpacity>
        {
          tabs.map((item: any, i: number) => (
            <TouchableOpacity
              key={i}
              onPress={() => { setActiveTab(item.id); set_url(item.url) }}
              style={{ marginRight: 10, borderRadius: 20, backgroundColor: activeTab == item.id ? MarketStyle.colorPrimaryMarket : 'transparent', borderColor: activeTab == item.id ? 'transparent' : '#ccc', borderWidth: 1, paddingVertical: 6, paddingHorizontal: 17, justifyContent: 'center' }} >
              <LibTextstyle textStyle='footnote' text={item.title} style={{ color: activeTab == item.id ? '#f1f1f1' : '#4E4E4E' }} />
            </TouchableOpacity>
          ))
        }
      </View>

      {
        totalItem != 0 &&
        <View style={{ marginHorizontal: 17, marginBottom: 10 }} >
          <Text allowFontScaling={false} style={{ fontFamily: 'Arial', fontSize: 12, color: '#4E4E4E' }} >{esp.lang("market/merchant_detail_product_list", "total_product", String(totalItem))}</Text>
        </View>
      }

      <LibInfinite
        key={buildUrl(_url) + counter}
        url={buildUrl(_url)}
        style={{ marginHorizontal: 5 }}
        keyExtractor={(item, i) => i.toString()}
        errorView={(e: string) => (<MarketEmpty msg={e} />)}
        onDataChange={(data: any, page: number) => { setUpData(data) }}
        injectData={upData}
        renderItem={renderItems}
        LoadingView={
          <LibSkeleton backgroundStyle={{ height: LibStyle.height }}>
            {
              [1, 1, 1, 1].map((x: any, i: number) => (
                <View key={i} style={{ marginHorizontal: 17, marginBottom: 10, borderWidth: 1, padding: 10, borderRadius: 5 }}>
                  <View style={{ flexDirection: 'row' }}>
                    <View style={{ width: 60, height: 60, borderRadius: 5, backgroundColor: 'orange' }} />
                    <View style={{ marginLeft: 10, flex: 1, justifyContent: 'space-between' }}>
                      <View style={{ width: '60%', height: 18, borderRadius: 10, backgroundColor: 'orange' }} />
                      <View style={{ width: '40%', height: 18, borderRadius: 10, backgroundColor: 'orange' }} />
                      <View style={{ flexDirection: 'row' }}>
                        <View style={{ flex: 1 }}>
                          <View style={{ width: '40%', height: 18, borderRadius: 10, backgroundColor: 'orange' }} />
                        </View>
                        <View style={{ flex: 1 }}>
                          <View style={{ width: '40%', height: 18, borderRadius: 10, backgroundColor: 'orange' }} />
                        </View>
                      </View>
                    </View>
                  </View>
                  <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 }}>
                    <View style={{ borderWidth: 1, flex: 1, padding: 10, alignItems: 'center', justifyContent: 'center', borderRadius: 5, marginRight: 10 }}>
                      <View style={{ width: '50%', height: 18, borderRadius: 10, backgroundColor: 'orange' }} />
                    </View>
                    <View style={{ borderWidth: 1, flex: 1, padding: 10, alignItems: 'center', justifyContent: 'center', borderRadius: 5 }}>
                      <View style={{ width: '50%', height: 18, borderRadius: 10, backgroundColor: 'orange' }} />
                    </View>
                    <LibIcon name="dots-vertical" />
                  </View>
                </View>
              ))
            }
          </LibSkeleton>
        }
      />

      <LibSlidingup ref={slideUp} >
        <View style={{ backgroundColor: 'white', borderTopLeftRadius: 15, borderTopRightRadius: 15, paddingBottom: 25 }} >
          <View style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }} >
            <TouchableOpacity onPress={() => { slideUp.current?.hide() }} >
              <LibIcon name='close' />
            </TouchableOpacity>
            <Text allowFontScaling={false} style={{ marginLeft: 15, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/merchant_detail_product_list", "sort_filter")}</Text>
          </View>
          <View style={{ marginHorizontal: 10 }} >
            {
              _sort.map((item: any, i: number) => (
                <TouchableOpacity key={i} onPress={() => {
                  setSort(item)
                  slideUp.current?.hide()
                }} style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }} >
                  <LibIcon name={item == sort ? "radiobox-marked" : "radiobox-blank"} color={MarketStyle.colorPrimaryMarket} style={{ marginRight: 15 }} />
                  <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 11, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{_sortTitle[i]}</Text>
                </TouchableOpacity>
              ))
            }
          </View>
        </View>
      </LibSlidingup>

    </View >

  )
}