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


import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/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 { MarketConfigProperty } from 'esoftplay/cache/market/config/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_label } from 'esoftplay/cache/market/input_label/import';
import { MarketInput_select } from 'esoftplay/cache/market/input_select/import';
import { MarketSection_menu } from 'esoftplay/cache/market/section_menu/import';
import { MarketToggle } from 'esoftplay/cache/market/toggle/import';
import { MarketUser_profileProperty } from 'esoftplay/cache/market/user_profile/import';
import { UserClass } from 'esoftplay/cache/user/class/import';

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


export interface MarketWithdrawArgs {
  from: 'dc' | 'merchant'
}

export interface MarketWithdrawProps {

}
export default function m(props: MarketWithdrawProps): any {
  const inputAmount = useRef<LibInput>(null)
  const [bank, setBank, getBank] = useSafeState<any>()
  const [resultUserVerif, setResultUserVerif] = useSafeState<any>()
  const [all, setAll] = useSafeState<number>(0)
  const [amount, setAmount] = useSafeState<number>(0)
  const [error, setError] = useSafeState(true)
  const user = UserClass.state().useSelector(s => s)
  const marketConfig = MarketConfigProperty.state().get()
  const { from } = LibNavigation.getArgsAll<any>(props)

  const title = from == "merchant" ? esp.lang("market/withdraw", "title_merchant") : from == 'dc' ? esp.lang("market/withdraw", "title_dc") : esp.lang("market/withdraw", "title_other")
  const bank_label = from == "merchant" ? esp.lang("market/withdraw", "wd_merchant") : from == 'dc' ? esp.lang("market/withdraw", "wd_dc") : esp.lang("market/withdraw", "wd_other")
  const saldo = from == "merchant" ? user?.saldo_merchant : from == 'dc' ? user?.saldo_dc : user?.saldo
  const min_withdraw = from == "merchant" ? marketConfig?.shop?.withdraw_min : from == "dc" ? marketConfig?.dc?.withdraw_min : user?.withdraw_min
  // const max_saldo = Math.max(saldo, inputAmount.current!.getText())


  const valid = bank && !error

  useEffect(() => {
    checkVerif()
  }, [])

  function checkVerif() {
    new LibCurl('user_verification', null, (res, msg) => {
      setResultUserVerif(res)
    }, (err) => {
      esp.log(err, "eror");
    }, 1)
  }

  function doWithdraw(pin?: string) {
    if (!getBank()) {
      LibToastProperty.show(esp.lang("market/withdraw", "empty_to"))
      return
    }
    if (inputAmount.current!.getText() == '') {
      LibToastProperty.show(esp.lang("market/withdraw", "empty_nominal"))
      return
    }

    var post = {
      amount: LibUtils.numberAbsolute(inputAmount.current!.getText()),
      payment_id: getBank().id,
      pin: pin
    }

    const _url = from == "merchant" ? "shop/merchant_withdraw_add" : from == 'dc' ? "mitra/dc_withdraw_add" : "user_withdraw_add"

    LibProgress.show(esp.lang("market/withdraw", "wd_wait"))
    new LibCurl(_url, post, (result, msg) => {
      LibProgress.hide()
      LibDialog.info(esp.lang("market/withdraw", "wd_ok"), msg)
      LibNavigation.reset()
      LibNavigation.navigate('notification/index')
    }, (error) => {
      MarketUser_profileProperty.update()
      LibProgress.hide()
      LibDialog.warning(esp.lang("market/withdraw", "wd_failed"), error?.message)
    }, 1)
  }

  if (!resultUserVerif) {
    return <LibLoading />
  }

  if (resultUserVerif?.status?.id !== 1) {
    LibNavigation.back()
    LibNavigation.navigate('withdraw/waiting')
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader onlyBack title={title} />
      <LibScroll onRefresh={() => MarketUser_profileProperty.update()} >
        <MarketInput_select
          containerStyle={{ marginTop: 10 }}
          label={bank_label}
          value={bank && bank.bank_name + ' (*' + bank.bank_number.substr(bank.bank_number.length - 4) + ')'}
          placeholder={esp.lang("market/withdraw", "select_bank")}
          onPress={() => {
              LibNavigation.navigateForResult('market/banks', { from: 'market/withdraw' }).then((bank) => { setBank(bank); })
          }}
        />
        <View style={{ marginHorizontal: 17, marginTop: 17 }}>
          <MarketInput_label label={esp.lang("market/withdraw", "total_wd")} />
          <LibInput
            ref={inputAmount}
            base
            placeholder={'0'}
            keyboardType="numeric"
            returnKeyType="done"
            onChangeText={(t) => {
              setAll(0)
              if ((parseInt(inputAmount.current!.getText()) > parseInt(saldo))) {
                inputAmount.current!.setError(esp.lang("market/withdraw", "saldo_not_enough"))
                setError(true)
                return
              }
              LibUtils.debounce(() => {
                setAmount(parseInt(inputAmount.current!.getText()))
                setAll(parseInt(inputAmount.current!.getText()) == parseInt(saldo) ? 1 : 0)
                setError(parseInt(min_withdraw) > (parseInt(inputAmount.current!.getText()) || 0))
              }, 50)
            }}
            mask="###.###.###.###.###.###"
            maskFrom="end"
            style={{ fontWeight: "bold", color: error ? LibStyle.colorRed : 'black', fontSize: 30, paddingVertical: 20, textAlign: 'center' }} />
        </View>
        <MarketSection_menu size="line" />
        {
          parseInt(min_withdraw) > 0 &&
          <LibTextstyle textStyle="caption2" text={esp.lang("market/withdraw", "wd_min", LibUtils.money(min_withdraw))} style={{ marginHorizontal: 17, marginTop: 5, marginBottom: 10, textAlign: 'right', color: "#888" }} />
        }
        <View style={{ flexDirection: "row", alignItems: 'center', paddingHorizontal: 17, paddingVertical: 10 }} >
          <View style={{ flex: 1 }} >
            <LibTextstyle text={esp.lang("market/withdraw", "wd_all")} textStyle="footnote" />
            <LibTextstyle text={LibUtils.money(saldo)} textStyle="footnote" style={{ fontWeight: "bold" }} />
          </View>
          <MarketToggle
            type={'success'}
            onChangeValue={() => {
              inputAmount.current!.setText(all == 0 ? saldo : "")
              setAll(all == 1 ? 0 : 1)
              setAmount(all == 0 ? saldo : "")
              setError(!!all)
            }}
            value={!!all} />
        </View>
        <MarketSection_menu size="small" />
        <View style={{ paddingHorizontal: 17, paddingVertical: 10 }} >
          <LibTextstyle text={esp.lang("market/withdraw", "wd_fee")} textStyle="footnote" style={{ flex: 1 }} />
          <LibTextstyle text={esp.lang("market/withdraw", "wd_no_fee")} textStyle="footnote" style={{ alignSelf: "flex-end" }} />
        </View>
        <MarketSection_menu size="line" />
        <View style={{ paddingHorizontal: 17, paddingVertical: 10 }} >
          <LibTextstyle text={esp.lang("market/withdraw", "fund_to_bank")} textStyle="footnote" style={{ flex: 1 }} />
          <LibTextstyle text={LibUtils.money(amount)} textStyle="footnote" style={{ fontWeight: "bold", alignSelf: "flex-end" }} />
        </View>
        <MarketSection_menu title={esp.lang("market/withdraw", "wd_info")} footer />
      </LibScroll>
      <View pointerEvents={!valid ? "none" : "auto"} style={{ paddingHorizontal: 17, marginTop: 4, marginBottom: 8 }} >
        <MarketButton
          colorBackground={!valid ? "#aaa" : undefined}
          textStyle={{ color: 'white' }}
          text={esp.lang("market/withdraw", "wd_button")} onPress={() => {
            if (!bank) return
            if (error) return

            LibNavigation.navigateForResult("market/payment_pin", undefined, 1132).then((p) => {
              if (p) {
                doWithdraw(p)
              }
            })

          }} />
      </View>
    </View>
  )
}