// withHooks
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/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 { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import { useEffect, useRef } from 'react';

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


export interface EventVoucher_multiArgs {

}
export interface EventVoucher_multiProps {

}

export type DataTicket = Array<{
  "list_id": string,
  "date_id": number,
  "ondate": string,
  "price_id": string,
  "price": string,
  "quota": string,
  "quota_used": string,
  "show_limit": number,
  "status": number,
  "show_price": number,
  "currency": string,
  "schedule": {
    "info": string,
    "artist": [],
  },
  "selected": number,
  "qty": string,
  "seat_autopick": number,
  "use_seat": string,
  "type": string,
  "tax": string,
  "term": Array<string>,
}>

export default function m(props: EventVoucher_multiProps): any {
  const { dataTicket, event_id } = LibNavigation.getArgsAll(props)
  let [data, setData, getData] = useSafeState<any>(dataTicket)
  let [dataPost, setDataPost, getDataPost] = useSafeState<any>()
  let voucherCode = useRef<LibInput>(null)
  const dialogInput = useRef<LibSlidingup>(null)


  useEffect(() => {
    // dialogInput.current?.show()
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  function checkVoucher() {
    let post = {
      voucher_code: voucherCode.current!.getText(),
      event_id: event_id,
      price_id: getDataPost().price_id,
      ondate: getDataPost().ondate,
      qty: dataTicket?.qty
    }


    let url = "event_booking_voucher_check"
    LibProgress.show(esp.lang("event/voucher", "check_wait"))
    new LibCurl(url, post, (res, msg) => {
      let newRes = {
        voucher_code: post?.voucher_code,
        ...res
      }
      // setResult(res)
      let a = LibObject.set(getData(), newRes)(getDataPost().index, 'voucher')
      setData(a)
      LibProgress.hide()
      LibToastProperty.show(msg)
      dialogInput?.current?.hide()
    }, (error) => {
      LibDialog.warning("Oops", error?.message)
      LibProgress.hide()

    }, 1)
  }

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/voucher", "header")} />
      <LibKeyboard_avoid style={{ flex: 1, marginBottom: 15 }}>
        <ScrollView>
          {
            data?.length > 0 && data?.map((item: any, i: number) => {
              return (
                <View style={{ borderRadius: 5, margin: 5, backgroundColor: '#fff' }}>

                  <View style={{ margin: 15, marginTop: 0 }}>
                    <View style={{ marginTop: 15, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'space-between' }}>
                      <Text allowFontScaling={false} style={{ flex: 1, fontWeight: 'bold' }}>{">"} {item.type}</Text>
                      {
                        item.hasOwnProperty('voucher') &&
                        <TouchableOpacity onPress={() => {
                          let a = LibObject.removeKeys(getData(), ['voucher'])(i)
                          setData(a)
                        }} style={{ flex: 1 }}>
                          <LibIcon name='close-circle' style={{ alignSelf: 'flex-end' }} color={LibStyle.colorRed} />
                        </TouchableOpacity>
                      }
                    </View>
                    <TouchableOpacity testID='voucher' onPress={() => {
                      let post = {
                        index: i,
                        price_id: item.price_id,
                        ondate: item.ondate,
                        type: item.type
                      }
                      setDataPost(post)
                      dialogInput.current?.show()
                    }} style={{ flex: 1, borderRadius: 10, borderColor: item.hasOwnProperty('voucher') ? LibStyle.colorGreen : "#c9c9c9", borderWidth: 1, backgroundColor: '#fff', padding: 7, marginTop: 10, marginBottom: 0, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
                      <Text allowFontScaling={false} style={{ flexWrap: 'wrap', marginLeft: 15, fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: item.hasOwnProperty('voucher') ? LibStyle.colorGreen : "#707070" }}>
                        {item.hasOwnProperty('voucher') ? esp.lang("bigbang/payment", "success_use_code") : esp.lang("bigbang/payment", "input_code")}
                        {item.hasOwnProperty('voucher') && <Text style={{ color: item.hasOwnProperty('voucher') ? LibStyle.colorGreen : "#000", fontWeight: 'bold' }}> {item?.voucher?.voucher_code}</Text>}
                      </Text>
                      <LibIcon name="chevron-right" color={item.hasOwnProperty('voucher') ? LibStyle.colorGreen : "#000"} />
                    </TouchableOpacity>
                  </View>
                </View>
              )
            })
          }
        </ScrollView>
      </LibKeyboard_avoid>
      <TouchableOpacity testID='claim_now' onPress={() => {
        LibNavigation.sendBackResult(getData())
      }}>
        <View style={{ marginHorizontal: 15, marginVertical: 10, height: 35, borderRadius: 17.5, backgroundColor: "#00b894", alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} >
          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: '#fff' }} >{esp.lang("bigbang/payment", "claim")}</Text>
        </View>
      </TouchableOpacity>

      <LibSlidingup ref={dialogInput} >
        <View style={[{ maxHeight: LibStyle.height * 0.7, borderTopLeftRadius: 10, borderTopRightRadius: 10, backgroundColor: '#fff' }]}>
          <View style={{ padding: 16, paddingBottom: 0, flexDirection: 'row', alignItems: 'center' }} >
            <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "ArialBold", fontSize: 18, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/voucher", "voucher_or_referral_code")}</Text>
            <Pressable onPress={() => dialogInput.current?.hide()} >
              <LibIcon name='close' />
            </Pressable>
          </View>
          <Text allowFontScaling={false} style={{ marginLeft: 16, marginTop: 10, fontSize: 14, fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{getDataPost()?.type}</Text>

          <LibInput
            ref={voucherCode}
            label=""
            autoCapitalize={"characters"}
            returnKeyType="go"
            onSubmitEditing={() => {
              checkVoucher()
            }}
            style={{ backgroundColor: LibStyle.colorGrey, letterSpacing: 0, fontSize: 30, textAlign: 'center' }} />
          <TouchableOpacity testID='use_voucher' onPress={() => {
            checkVoucher()
          }} style={{ alignSelf: 'flex-end', marginBottom: 15, marginRight: 15, 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>
          </TouchableOpacity>
        </View>

      </LibSlidingup>
    </View>
  )
}