// withHooks
import AsyncStorage from '@react-native-async-storage/async-storage';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibList } from 'esoftplay/cache/lib/list/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/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 { MarketStyle } from 'esoftplay/cache/market/style/import';
import { UseCurl } from 'esoftplay/cache/use/curl/import';
import esp from 'esoftplay/esp';

import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import React, { useEffect, useRef } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';

export interface MarketProduct_categoryProps {

}

const _state = useGlobalState<any[]>([], { persistKey: "market_product_category", inFile: true })
export function state(): useGlobalReturn<any> {
  return _state
}

function getCategories(last_update: string) {
  new LibCurl("shop/product_cat", null, (res, msg) => {
    AsyncStorage.setItem('market_product_category_update_id', String(last_update))
    _state.set(res)
  })
}

export function update(): void {
  //delete soon
  AsyncStorage.removeItem('market_product_category')
  //delete soon

  AsyncStorage.getItem('market_product_category_update_id').then((e) => {
    fetch(esp.config("url") + "images/modules/shop/lastupdate/product_cat.json").then((r) => r.json())
      .then((x) => {
        if (x.hasOwnProperty("last_update")) {
          if (x.last_update != e || _state.get().length == 0) {
            getCategories(x.last_update)
          }
        } else {
          getCategories(x.last_update)
        }
      })
  })
}

const stateUpdate = useGlobalState<any>(undefined, { persistKey: "market_product_category_update_id" })

export default function m(props: MarketProduct_categoryProps): any {
  const selectedDefault = LibUtils.getArgs(props, 'selected', [])
  const scrollRef = useRef<ScrollView>(null)
  const stripRef = useRef<ScrollView>(null)
  const [data, setData] = _state.useState()
  const [updateId, setUpdateId] = stateUpdate.useState()
  const [curl, loading, error] = UseCurl(false)
  const [selected, setSelected] = useSafeState<any[]>(selectedDefault)
  const cat = selected && selected[selected.length - 1]

  function update(last_update: string) {
    new LibCurl("shop/product_cat", null, (res, msg) => {
      setUpdateId(String(last_update))
      setData(res)
    })
  }

  useEffect(() => {
    fetch(esp.config("url") + "images/modules/shop/lastupdate/product_cat.json").then((r) => r.json())
      .then((x) => {
        if (x.hasOwnProperty("last_update")) {
          if (x.last_update != updateId || data.length == 0) {
            update(x.last_update)
          }
        } else {
          update(x)
        }
      })
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  useEffect(() => {
    LibUtils.debounce(() => {
      try {
        scrollRef.current?.scrollToEnd()
        stripRef.current?.scrollToEnd()
      } catch (error) {

      }
    }, 100);
  }, [selected])


  return (
    <View style={{ flex: 1 }} >
      <MarketHeader
        leftIcon={{ name: "close", onPress: () => LibNavigation.back() }}
        title={esp.lang("market/product_category", "header_title")}
        rightView={() => (<View style={{ height: 50, width: 50 }} />)} />
      {
        loading ? <LibLoading /> :
          error ? <MarketEmpty msg={error} />
            :
            <View style={{ flex: 1 }} >
              <View style={{ backgroundColor: "#fff" }} >
                {
                  selected?.length == 0 &&
                  <Text allowFontScaling={false} style={{ margin: 10, marginRight: 0, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 21, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/product_category", "select_category")}</Text>
                }
                <ScrollView ref={stripRef} horizontal style={{ marginLeft: 10 }} >
                  {
                    selected?.map?.((item: any, index: number) => (
                      <TouchableOpacity
                        key={index}
                        onPress={() => scrollRef.current?.scrollTo({ x: LibStyle.width * index })}
                        style={{ marginVertical: 5, paddingVertical: 8, paddingHorizontal: 12, marginRight: 10, borderRadius: 16, flexDirection: "row", alignItems: 'center', borderWidth: 1, borderColor: (index == selected.length - 1) ? 'transparent' : '#ccc', backgroundColor: (index == selected.length - 1) ? MarketStyle.colorPrimaryMarket : 'white' }} >
                        <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: (index == selected.length - 1) ? 'white' : "#03192a" }} >{item.title}</Text>
                      </TouchableOpacity>
                    ))
                  }
                </ScrollView>
              </View>
              <ScrollView
                ref={scrollRef}
                horizontal
                pagingEnabled
                showsHorizontalScrollIndicator={true}
                style={{ flex: 1 }} >
                <List
                  key={0}
                  data={data?.filter((x: any) => x.par_id == 0)}
                  selected={selected}
                  onCategorySelected={() => {
                  }}
                  onSelectItem={(x: any) => {
                    let newSelected = selected?.slice(0, 0)
                    newSelected?.push(x)
                    setSelected(newSelected)
                  }}
                />
                {
                  selected && selected?.length > 0 &&
                  selected?.map((item, index) => (
                    <List
                      key={index + 1}
                      data={data?.filter((x: any) => x.par_id == item.id)}
                      selected={selected}
                      onCategorySelected={() => {
                        const cat = selected[selected.length - 1]
                        if (cat)
                          new LibCurl("shop/product_spec?cat_id=" + cat.id, null,
                            (res, msg) => {
                              LibNavigation.sendBackResult({ spec: res, cat: selected }, LibNavigation.getResultKey(props))
                            }, (msg) => {
                              LibNavigation.sendBackResult({ spec: [], cat: selected }, LibNavigation.getResultKey(props))
                            }, 1
                          )
                      }}
                      onSelectItem={(x: any) => {
                        let newSelected = selected.slice(0, index + 1)
                        newSelected.push(x)
                        setSelected(newSelected)
                      }}
                    />
                  ))
                }
              </ScrollView>
              {
                cat && (data?.filter((x: any) => x.par_id == cat.id).length == 0) &&
                <MarketButton
                  text={esp.lang("market/product_category", "btn_save")}
                  buttonStyle={{ marginHorizontal: 17, marginVertical: 10, borderRadius: 20 }}
                  textStyle={{ color: 'white' }}
                  onPress={() => {
                    if (data?.filter((x: any) => x.par_id == cat.id).length == 0) {
                      new LibCurl("shop/product_spec?cat_id=" + cat.id, null,
                        (res, msg) => {
                          LibNavigation.sendBackResult({ spec: res, cat: selected }, LibNavigation.getResultKey(props))
                        }, (msg) => {
                          LibNavigation.sendBackResult({ spec: [], cat: selected }, LibNavigation.getResultKey(props))
                        }, 1
                      )
                    } else {
                      LibToastProperty.show(esp.lang("market/product_category", "empty_category"))
                    }
                  }} />
              }
            </View>
      }
    </View >
  )
}


function List(props: any) {
  const scroll = useRef<LibList>(null)
  return (
    <View style={{ flex: 1, width: props.data.length == 0 ? 0 : LibStyle.width }} >
      {
        props.data.length == 0 ?
          <View style={{ flex: 1 }} />
          :
          <View style={{ flexDirection: 'row', flex: 1 }} >
            <LibList
              ref={scroll}
              data={props.data}
              renderItem={(item: any, index: number) => {
                const isSelected = props.selected.some((x: any) => x.id == item.id)
                return (
                  <TouchableOpacity onPress={() => { props.onSelectItem(item) }} style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: 17, paddingVertical: 16, borderBottomWidth: 1, borderBottomColor: '#eee' }} >
                    <LibTextstyle textStyle="callout" text={item.title} style={{ flex: 1, color: isSelected ? MarketStyle.colorPrimaryMarket : '#333' }} />
                    <LibIcon.SimpleLineIcons name={"check"} color={isSelected ? MarketStyle.colorPrimaryMarket : "transparent"} />
                  </TouchableOpacity>
                )
              }}
            />
            <View style={{ width: 1, backgroundColor: '#eee' }} />
          </View>
      }
    </View>
  )
}
