// 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 { LibList } from 'esoftplay/cache/lib/list/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/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 { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketCheckout_voucher_item } from 'esoftplay/cache/market/checkout_voucher_item/import';
import { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_label } from 'esoftplay/cache/market/input_label/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

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


export interface MarketCheckout_voucherArgs {

}
export interface MarketCheckout_voucherProps {

}
export default function m(props: MarketCheckout_voucherProps): any {

  const { url, cart_ids, courier_ids, payment_id, selectedVoucher, bill_total, shipping, address_id } = LibNavigation.getArgsAll<any>(props)
  const [result, setResult] = useSafeState<any>()
  const [error, setError] = useSafeState<any>()
  const [selectVoucher, setSelectVoucher, getVoucher] = useSafeState<any>(/* selectedVoucher ||  */[])
  let voucherCode = React.useRef<LibInput>(null)
  const [showText, setShowText] = useSafeState<boolean>(false)


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

  function loadData() {
    let post = {
      cart_ids: cart_ids,
      courier_ids: JSON.stringify(courier_ids),
      payment_id: payment_id,
      bill_total: bill_total
    }
    LibProgress.show(esp.lang("market/checkout_voucher", "load_data_wait"))
    new LibCurl(url, post, (res, msg) => {
      setResult(res)
      LibProgress.hide()
      esp.log(res, "res");
    }, (err) => {
      LibProgress.hide()
      setError(err?.message)
    }, 1)
  }

  function useCode() {

    if (voucherCode?.current?.getText() == '') {
      voucherCode?.current?.setError(esp.lang("market/checkout_voucher", "toast_empty_code"))
      return
    }

    let post = {
      cart_ids: cart_ids,
      shipping: JSON.stringify(Object.values(shipping)),
      payment_id: payment_id,
      code: voucherCode?.current?.getText(),
      address_id: address_id,
    }

    LibProgress.show(esp.lang("market/checkout_voucher", "wait"))
    new LibCurl("shop/product_cart_checkout_voucher_check", post, (res, msg) => {
      setShowText(true)
      LibProgress.hide()
      esp.log(res, "res");
      setSelectVoucher([res.voucher])
    }, (err) => {
      esp.log(err, "err");
      LibProgress.hide()
      // setError(err?.message)
    }, 1)
  }

  function useVoucher() {
    let voucherIds = getVoucher()?.map((it: any) => it.id)
    let post = {
      voucher_ids: JSON.stringify(voucherIds),
      payment_id: payment_id,
      cart_ids: cart_ids,
      courier_ids: JSON.stringify(courier_ids),
      shipping: JSON.stringify(Object.values(shipping)),
      address_id: address_id,
    }

    LibProgress.show(esp.lang("market/checkout_voucher", "use_vouceher_wait"))
    new LibCurl("shop/product_cart_checkout_voucher_calculation", post, (res, msg) => {
      // setResult(res)
      let a = {
        voucher_selected: getVoucher(),
        voucher_amount: res
      }
      LibNavigation.sendBackResult(a)
      LibProgress.hide()
    }, (error) => {
      LibProgress.hide()
      LibDialog.warning(esp.lang("market/checkout_voucher", "use_voucher_failed"), error?.message)
      // LibNavigation.back()
    }, 1)
  }

  // ini belum kepakai
  function useVouchers(item: any, id: string) {
    let _item = [...getVoucher()]
    let index = _item.map((x: any) => x.id).indexOf(id)

    if (_item.some((x: any) => id == x.id)) {
      _item = LibObject.splice(_item, index, 1)()
    } else {
      _item = LibObject.push(_item, item)()
    }
    setSelectVoucher([..._item])
  }

  // if (!result || !error) {
  //   return <LibLoading />
  // }

  function renderItem(item: any, i: number) {
    return (
      <MarketCheckout_voucher_item
        key={i}
        {...item}
        onSelected={() => {
          setSelectVoucher([item])
          setShowText(false)
          voucherCode?.current?.setText("")
          // script dibawah ini untuk nanti jika bisa milih banyak voucher
          // useVouchers(item, item.id)
        }}
        selected={selectVoucher?.some((x: any) => x.id == item.id || item.id == x.product_id)}
        showDetail
        onNavigate={() => {
          LibNavigation.navigate('market/checkout_voucher_detail', { url: item.url_detail })
        }}
      />
    )
  }

  return (
    <View style={styleId_qpkod}>
      <MarketHeader onlyBack title={esp.lang("market/checkout_voucher", "header_title")} rightView={() => (
        <TouchableOpacity onPress={() => {
          setSelectVoucher([])
          voucherCode?.current?.setText("")
          setShowText(false)
        }} style={styleId_ZnTxdz} >
          <LibTextstyle textStyle="callout" text={esp.lang("market/checkout_voucher", "text_reset")} style={styleId_ZwGcPJ} />
        </TouchableOpacity>
      )} />

      <LibList
        data={result}
        onRefresh={loadData}
        ListHeaderComponent={
          esp.isDebug("input voucher") &&
          <View style={{ marginVertical: 15, marginBottom: 0, }}>
            <View style={{ marginLeft: 15 }}>
              <MarketInput_label label={esp.lang("market/checkout_voucher", "label_input")} />
            </View>
            <LibInput
              ref={voucherCode}
              label=""
              editable={showText ? false : true}
              autoCapitalize={"characters"}
              returnKeyType="go"
              onSubmitEditing={useCode}
              style={{ marginTop: -20, backgroundColor: LibStyle.colorGrey, textAlign: 'center' }} />
            {
              showText &&
              <Text allowFontScaling={false} style={{ marginLeft: 15, fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorPrimary }} >{esp.lang("market/checkout_voucher", "success_use")}</Text>
            }
            <Pressable onPress={() => { !showText && useCode() }}>
              <View style={{ alignSelf: 'flex-end', marginRight: 15, marginLeft: 10, width: 68, height: 35, borderRadius: 3, backgroundColor: showText ? '#8e8e8e' : LibStyle.colorGreen, alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: '#fff' }}>{esp.lang("bigbang/payment", "button_use")}</Text>
              </View>
            </Pressable>

            {
              showText && selectVoucher?.length > 0 &&
              <MarketCheckout_voucher_item
                {...selectVoucher[0]}
                selected={selectVoucher?.some((x: any) => x.id == selectVoucher[0].id || selectVoucher[0].id == x.product_id)}
                showDetail
                onNavigate={() => {
                  esp.log("dipencet");
                  LibNavigation.navigate('market/checkout_voucher_detail', { url: selectVoucher[0].url_detail })
                }}
              />
            }

            <View style={{ marginVertical: 15, marginBottom: 0, height: 4, backgroundColor: LibStyle.colorBgGrey }} />

          </View>
        }
        ListEmptyComponent={<MarketEmpty msg={error} />}
        renderItem={(item, i) => {
          return (
            <View key={i} style={{ paddingVertical: 15, borderBottomWidth: 1, borderBottomColor: LibStyle.colorBgGrey }}>
              <Text allowFontScaling={false} style={{ margin: 15, marginTop: 0, marginBottom: 0, flexWrap: 'wrap', flex: 1, fontSize: 16, fontWeight: 'bold' }}>{item?.merchant_name}</Text>

              {
                item?.vouchers?.length > 0 && item?.vouchers?.map(renderItem)
              }

            </View>
          )
        }}
      />
      <View style={styleId_Z2qlY6B}>
        <MarketButton onPress={() => {
          if (selectVoucher.length > 0) {
            useVoucher()
          } else {
            LibToastProperty.show(esp.lang("market/checkout_voucher", "empty_voucher"))
          }
        }} text={esp.lang("market/checkout_voucher", "use_voucher")} colorBackground={selectVoucher.length > 0 ? MarketStyle.colorPrimaryMarket : LibStyle.colorGrey} />
      </View>
    </View>
  )
}
const styleId_qpkod: any = { flex: 1, backgroundColor: '#fff' }
const styleId_ZnTxdz: any = { height: 50, justifyContent: 'center', paddingRight: 17 }
const styleId_ZwGcPJ: any = { color: MarketStyle.colorPrimaryMarket }
const styleId_Z2qlY6B: any = { padding: 10, backgroundColor: '#fff' }
