// withHooks

import { EventDialog_custom } from 'esoftplay/cache/event/dialog_custom/import';
import { EventDistribution_lock } from 'esoftplay/cache/event/distribution_lock/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventPayment_subscribeProperty } from 'esoftplay/cache/event/payment_subscribe/import';
import { EventRandomseat } from 'esoftplay/cache/event/randomseat/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/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 { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { PaymentTicketProperty } from 'esoftplay/cache/payment/ticket/import';
import esp from 'esoftplay/esp';
import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import { useTimeout } from 'esoftplay/timeout';
import LottieView from 'lottie-react-native';
import React, { useEffect, useRef } from 'react';
import { ScrollView, Text, View } from 'react-native';


export interface EventLoading_pageArgs {

}
export interface EventLoading_pageProps {
  post: any
  url: string
  isSecure: number
  secureParam?: string
  title: string
  amount?: any
  send_image?: any
  send_name?: any
  send_account?: any
  receive_image?: any
  receive_name?: any
  receive_account?: any
  currency?: string
  order_type?: string
}

const loadingState = useGlobalState({}, { persistKey: 'event/loading_page' })

export function state(): useGlobalReturn<any> {
  return loadingState
}


export default function m(props: EventLoading_pageProps): any {
  const {
    post,
    url,
    isSecure, // untuk curl yang pakai .secure()
    secureParam, // contoh kasus di PPOB
    title, // title di header
    amount,
    send_image,
    send_name,
    send_account,
    receive_image,
    receive_name,
    receive_account,
    currency
  }: any = LibNavigation.getArgsAll(props)
  const animation = useRef<LottieView>(null)
  const timeout = useTimeout()
  const curr = currency ? currency : ''

  const sendBackResult = LibNavigation.useBackResult(props)

  useEffect(() => {
    // loadingState.reset()
    loadingState.set(LibObject.set(loadingState.get(), LibNavigation.getArgsAll(props))(post.trx_id))
    doAction()
    timeout(() => {
      animation.current?.play()
    }, 300);
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  function handleError(error: any) {
    LibProgress.hide()
    LibNavigation.back()
    loadingState.set(LibObject.unset(loadingState.get(), post.trx_id)())
    const ticketNotAvailableCodes = ['EV034', 'EV036', 'EV038', 'EV039', 'EV040']
    if (ticketNotAvailableCodes.includes(error.status_code)) {
      LibNavigation.back()
      // LibNavigation.navigate(post?.is_multi == 1 ? 'event/ticket_list2' : 'event/ticket_list')
    }
    if (error.status_code == 'EV033') {
      LibDialog.custom(
        <EventRandomseat
          onPressOk={() => {
            LibDialog.hide()
            PaymentTicketProperty.stateRandomSeat.set("2")
            EventPayment_subscribeProperty.reBooking.trigger()
          }}
          onPressNo={() => LibDialog.hide()}
        />
      )
    } else if (error?.status_code == "EV045") {
      EventDistribution_lock(() => {
        EventPayment_subscribeProperty.reTryBooking.trigger(post)
      })
      // LibDialog.custom(
      //   <ComponentDialog_custom
      //     icon={"close-circle"}
      //     color={LibStyle.colorRed}
      //     msg={error?.message || esp.lang("bigbang/loading_page", "booking_not_complete")}
      //     onPressOK={() => {
      //       LibDialog.hide()
      //       PaymentTicketProperty.reTryBooking.trigger(post)
      //     }}
      //     onPressCancel={() => { LibDialog.hide() }}
      //   />
      // )
    } else if (error?.status_code == "PY0254") {
      LibDialog.custom(
        <EventDialog_custom
          showCountdown
          icon={"close-circle"}
          color={LibStyle.colorRed}
          msg={error?.message || esp.lang("bigbang/loading_page", "booking_not_complete")}
          onPressOK={() => {
            LibDialog.hide()
            EventPayment_subscribeProperty.reTryBooking.trigger(post)
          }}
          onPressCancel={() => { LibDialog.hide() }}
        />
      )
    } else {
      if (error?.status_code != "GE043")
        LibDialog.warningConfirm(esp.lang("event/loading_page", "oops"), error?.message, esp.lang("event/loading_page", "back"), () => {

        }, "", () => { })
    }
  }

  function doAction() {

    if (isSecure && isSecure == 1) {
      new LibCurl().secure(secureParam ? secureParam : 'get_token')()(url, post ? post : null, (result, msg) => {
        LibProgress.hide()
        loadingState.set(LibObject.unset(loadingState.get(), post.trx_id)())
        let dataSB = {
          ok: 1,
          url: result?.url,
          ...result
        }

        sendBackResult(dataSB)

      }, (error) => {
        handleError(error)
      }, 1)
    } else {
      new LibCurl(url, post ? post : null, (result, msg) => {
        LibProgress.hide()
        loadingState.set(LibObject.unset(loadingState.get(), post.trx_id)())
        let dataSB = {
          ok: 1,
          url: result?.url,
          ...result
        }

        sendBackResult(dataSB)
      }, (error) => {
        handleError(error)
      }, 1)
    }
  }



  return (
    <View style={{ flex: 1, backgroundColor: "#fff" }}>
      <EventHeader title={title} />
      <ScrollView style={{ padding: 20 }}>
        <View style={{ alignItems: 'center' }} >
          <LottieView
            ref={animation}
            loop={true}
            style={{
              width: 150,
              height: 150,
            }}
            source={esp.assets('pending.json')}
          // OR find more Lottie files @ https://lottiefiles.com/featured
          // Just click the one you like, place that file in the 'assets' folder to the left, and replace the above 'require' statement
          />
        </View>
        <Text allowFontScaling={false} style={{ alignSelf: 'center', textAlign: 'center', fontFamily: 'ArialBold', fontSize: 17, marginTop: 30, color: '#4a4a4a' }} >{title}</Text>
        <Text style={{ alignSelf: 'center', textAlign: 'center', fontFamily: 'ArialBold', fontSize: 30, marginTop: 10, color: LibStyle.colorPrimary }} >{LibUtils.money(amount, curr)}</Text>

        <LibTextstyle text={esp.lang("event/loading_page", "from")} textStyle="m_overline" style={{ color: '#999', marginTop: 40 }} />
        <View style={{ flexDirection: 'row', marginTop: 5, alignItems: 'center' }} >
          <LibPicture style={{ height: 40, width: 40, borderRadius: 20, backgroundColor: '#f1f2f3', marginRight: 20 }} source={send_image && send_image == "" ? esp.assets('icons/ic_no_image_merchant.png') : { uri: send_image }} />
          <View style={{ flex: 1 }} >
            <LibTextstyle text={send_name} textStyle={'body'} />
            {
              send_account &&
              <LibTextstyle text={send_account} textStyle={'footnote'} style={{ color: "#888" }} />
            }
          </View>
        </View>

        <LibTextstyle text={esp.lang("event/loading_page", "receiver")} textStyle="m_overline" style={{ color: '#999', marginTop: 15 }} />
        <View style={{ flexDirection: 'row', marginTop: 5, alignItems: 'center' }} >
          <LibPicture style={{ height: 40, width: 40, borderRadius: 20, backgroundColor: '#f1f2f3', marginRight: 20 }} source={receive_image && receive_image == "" ? esp.assets('icons/ic_no_image_merchant.png') : { uri: receive_image }} />
          <View style={{ flex: 1 }} >
            <LibTextstyle text={receive_name} textStyle={'body'} />
            {
              receive_account &&
              <LibTextstyle text={receive_account} textStyle={'footnote'} style={{ color: "#888" }} />
            }
          </View>
        </View>

      </ScrollView>
      {/* <EventButton
        label='Refresh'
        onPress={doAction}
        backgroundColor={LibStyle.colorPrimary}
        style={{ margin: 15 }}
      /> */}
    </View>
  )
}