// withHooks
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventLabel_input } from 'esoftplay/cache/event/label_input/import';
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 { 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 { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { UseTasks } from 'esoftplay/cache/use/tasks/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import { useEffect } from 'react';

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


export interface EventVoucher2Args {

}
export interface EventVoucher2Props {

}

const useTasks = UseTasks()

export default function m(props: EventVoucher2Props): any {
  let { event_id, dataTicket }: any = LibNavigation.getArgsAll(props)
  let voucherCode = React.useRef<LibInput>(null)
  let [, setData, getData] = useSafeState<any>(dataTicket)

  const [, setCounterNo, getCounterNo] = useSafeState(0)

  useEffect(() => {
    let a = dataTicket?.length > 0 && dataTicket?.map((item: any, i: number) => {
      return ({
        ...item,
        index: i
      })
    })
    setData(a)
    // dialogInput.current?.show()
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  const [checkVoucers, resetCheckVoucers] = useTasks((item: any) => new Promise((next) => {
    curlVoucher(item, () => {
      next()
    })
  }), () => {
    LibProgress.hide()
    if (getCounterNo() == getData()?.length) {

    } else {
      LibNavigation.sendBackResult(getData())
    }
  })


  function curlVoucher(item: any, cb: () => void) {
    let post = {
      voucher_code: voucherCode.current!.getText(),
      event_id: event_id,
      price_id: item?.price_id,
      ondate: item?.ondate,
      qty: item?.qty
    }


    let url = "event_booking_voucher_check"
    LibProgress.show(esp.lang("event/voucher", "check_wait"))
    new LibCurl(url, post, (res, msg) => {

      let x = new LibObject(getData()).update((it: any) => {
        it.discount_id = res?.id
        it.discount_generated_id = res?.generated_id
        it.discount_amount = res?.amount
        it.discount_type = res?.amount_type
        return it
      })(item.index).update((it2: any) => {
        return ({
          ...it2,
          ...res,
          voucher_code: post?.voucher_code
        })
      })(item.index, 'voucher').value()
      setData(x)
      cb()
      LibProgress.hide()
      LibToastProperty.show(msg)
    }, (error) => {
      setCounterNo(getCounterNo() + 1)
      cb()
      if (getCounterNo() == getData()?.length) {
        LibDialog.warning("Oops", error?.message)
      }
      LibProgress.hide()

    }, 1)
  }


  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <EventHeader title={esp.lang("event/voucher", "header")} />
      <ScrollView>
        <View style={{ margin: 15, marginTop: 0 }}>
          <EventLabel_input label={esp.lang("event/voucher", "voucher_or_referral_code")} mandatory />
        </View>
        <View testID='input_voucher'>
          <LibInput
            ref={voucherCode}
            label=""
            editable={true}
            autoCapitalize={"characters"}
            returnKeyType="go"
            onSubmitEditing={() => {
              resetCheckVoucers()
              setCounterNo(0)
              checkVoucers(getData())
            }}
            style={{ marginTop: -20, backgroundColor: LibStyle.colorGrey, letterSpacing: 0, fontSize: 30, textAlign: 'center' }} />
        </View>
        <TouchableOpacity testID='use_voucher' onPress={() => {
          resetCheckVoucers()
          setCounterNo(0)
          checkVoucers(getData())
        }}>
          <View style={{ alignSelf: 'flex-end', marginRight: 15, marginBottom: 10, marginLeft: 10, width: 68, height: 35, borderRadius: 3, backgroundColor: 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>
        </TouchableOpacity>

      </ScrollView>

    </View>
  )
}