// withHooks

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 { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/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 { Keyboard, Pressable, View } from 'react-native';


export interface MarketLocationProps {

}

const _state = useGlobalState([], { persistKey: 'market_location', loadOnInit: true })

export function state(): useGlobalReturn<any> {
  return _state
}

export default function m(props: MarketLocationProps): any {
  const [query, setQuery] = useSafeState("")
  const [curl, loading, err] = UseCurl()
  const [location, setLocation] = state().useState()
  const inputQuery = useRef<MarketInput_square>(null)
  const key = LibNavigation.getResultKey(props)

  useEffect(() => {
    if (!location?.length) {
      curl("location", null, (r) => {
        setLocation(r.filter((x: any) => x.type == 3))
      })
    }
    inputQuery?.current?.focus()
    return () => LibNavigation.cancelBackResult(key)
  }, [])


  function renderRow(prop: any) {
    return (
      <View style={{ borderBottomWidth: 1, borderBottomColor: "#ededed" }} >
        <Pressable
          onPress={() => {
            Keyboard?.dismiss?.()
            LibNavigation.sendBackResult(prop, key)
          }}
          style={{ paddingHorizontal: 17, paddingVertical: 10 }} >
          <LibTextstyle textStyle="body" text={prop?.title} />
          <LibTextstyle textStyle="footnote" text={prop?.detail} style={{ color: "#888" }} />
        </Pressable>
      </View>
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: "white" }} >
      <MarketHeader leftIcon={{ name: "close", onPress: () => { LibNavigation.back() } }} title={esp.lang("market/location", "location")} />
      <MarketInput_square
        ref={inputQuery}
        autoFocus
        placeholder={esp.lang("market/location", "search_placeholder")} onChangeText={(r) => LibUtils.debounce(() => setQuery(r), 500)} />
      {
        (loading && location.length == 0) ? <LibLoading />
          : err ? <MarketEmpty msg={err} />
            :
            <LibList
              data={location.filter((loc: any) => loc.detail.toLowerCase().includes(query.toLowerCase()))}
              renderItem={renderRow}
              keyboardShouldPersistTaps="handled"
            />
      }
    </View>
  )
}

