// withHooks
import { LibCurl } from 'esoftplay/cache/lib/curl/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 { MarketAddress_item } from 'esoftplay/cache/market/address_item/import';
import { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import useGlobalSubscriber, { useGlobalSubscriberReturn } from 'esoftplay/subscribe';

import React, { useEffect } from 'react';
import { View } from 'react-native';


export interface MarketAddressProps {

}
export interface MarketAddressItem {
  withKey: number,
  address: string,
  address_merchant?: string,
  address_mitra?: string,
  address_primary: string,
  address_return: string,
  id: string,
  location_id: string,
  location_latlong: string,
  location_name: string,
  name: string,
  phone: string,
  zipcode: string,
  recipient: string,
}
const subs = useGlobalSubscriber()
export function subscribe(): useGlobalSubscriberReturn {
  return subs
}
export default function m(props: MarketAddressProps): any {
  const { from } = LibNavigation.getArgsAll<any>(props)
  const [data, setData] = useSafeState([])
  const [error, setError] = useSafeState<any>()

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

  subs.useSubscribe(() => {
    list()
  })

  function list() {
    new LibCurl('shop/member_location', null, (res, msg) => {
      setData(res)
    }, (error) => {
      setError(error)
    })
  }

  function renderItemAddress(item: any, idx: number) {
    return (
      <MarketAddress_item key={idx} {...item} from={from} withKey={LibNavigation.getResultKey(props)} />
    )
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader onlyBack title={esp.lang("market/address", "header_title")} rightIcon={{ name: "plus", onPress: () => { LibNavigation.navigate("market/address_add", { from: from }) } }} />
      <LibList
        data={data}
        onRefresh={list}
        keyExtractor={(x, i) => i.toString()}
        ListEmptyComponent={
          error ?
            <MarketEmpty msg={error?.message} />
            :
            <LibLoading />
        }
        renderItem={renderItemAddress}
      />
    </View>
  )
}