// withHooks

import { applyStyle } from 'esoftplay';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventQr_bg } from 'esoftplay/cache/event/qr_bg/import';
import { EventTransaction } from 'esoftplay/cache/event/transaction/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibWorkloop } from 'esoftplay/cache/lib/workloop/import';
import { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useGlobalState from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import LottieView from "lottie-react-native";
import React, { useEffect, useRef } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';
import QRCode from 'react-native-qrcode-svg';

export interface EventCounter_cashier_sellArgs {

}
export interface EventCounter_cashier_sellProps {

}

const state = useGlobalState<any>({}, { persistKey: 'event_counter_cashier_sell_scan' })

export function syncToServer(trx_id?: string, qrTicket?: string, cb?: (state: number) => void) {
  if (qrTicket && trx_id) {
    state.set(LibObject.set(state.get(), trx_id)(qrTicket))
  }
  const event_id = UserClass?.state?.()?.get()?.is_seller?.[0]?.id
  if (event_id) {
    Object.keys(state.get() || {}).forEach((key, index) => {
      if (state.get()[key]) {
        const trx_id = state.get()[key]
        const post = {
          event_id,
          trx_id: trx_id,
          qrs: key
        }
        new LibCurl('event_seller_ticket_sell', post, (res, msg) => {
          if (res.length > 0) {
            let dt = state.get();
            res.forEach(({ qr, status }: any) => {
              if (qr == qrTicket && cb) {
                cb(status)
              }
              if (status != 0)
                delete dt[qr]
            })
            state.set(dt || {})
            if (Object.keys(state.get() || {}).length > 0)
              LibWorkloop.execNextTix(syncToServer)
          }
        }, (err) => {
          if (Object.keys(state.get() || {}).length > 0)
            LibWorkloop.execNextTix(syncToServer)
        }, 1)
      }
    })
  }
}


const statusText = (status: number | string): any => {
  const statusTex: any = {
    "0": esp.lang("event/counter_cashier_sell", "status_0"),
    "1": esp.lang("event/counter_cashier_sell", "status_1"),
    "2": esp.lang("event/counter_cashier_sell", "status_2")
  }
  return statusTex[status] || "Loading..."
}


export default function m(props: EventCounter_cashier_sellProps): any {

  const { qr } = LibNavigation.getArgsAll<any>(props);
  const [trxId] = useSafeState(EventTransaction().getTrxId())
  const is_seller = UserClass?.state?.()?.get()?.is_seller?.[0]
  const [status, setStatus] = useSafeState(-1)

  const animation = useRef<LottieView>(null)

  useEffect(() => {
    if (status > -1) {
      animation.current?.play()
    } else {
      syncToServer(trxId, qr, setStatus)
    }
  }, [status])

  return (
    <View style={{ backgroundColor: 'white', flex: 1 }} >
      <EventHeader title={esp.lang("event/counter_cashier_sell", "header")} subtitle={is_seller?.name} bgColor={"#6A0740"} titleColor="#fff" notif />
      <ScrollView>
        <View style={{ alignItems: 'center', paddingTop: 50, flex: 1 }} >
          <LottieView
            ref={animation}
            loop={false}
            style={{ width: 200, height: 200, }}
            source={esp.assets(status == 1 ? 'success.json' : status == 2 ? 'reject.json' : 'pending.json')} />
          <LibTextstyle style={{ textAlign: 'center', margin: 16 }} textStyle='m_button' text={statusText(status)} />
          <EventQr_bg>
            <QRCode ecl="H"
              size={200}
              value={qr}
            />
          </EventQr_bg>
          <LibTextstyle textStyle='title2' text={qr} style={{ marginTop: 10, marginBottom: 20, fontWeight: 'bold' }} />
        </View>
      </ScrollView>
      <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', marginBottom: 20 }} >
        <TouchableOpacity onPress={() => { LibNavigation.back() }} style={applyStyle({ width: (LibStyle.width - 40) * 0.5, borderWidth: 2, borderColor: LibStyle.colorRed, height: 40, borderRadius: 16, backgroundColor: LibStyle.colorRed, flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
          <LibIcon size={18} color={'white'} name="close" style={applyStyle({ fontWeight: 'bold', transform: [{ rotate: '180deg' }] })} />
          <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: 'white', marginLeft: 10 })} >{esp.lang("event/counter_cashier_sell", "done")}</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => {
          LibNavigation.replace('component/scanner', {
            event_id: is_seller?.id,
            fromPage: 'event/counter_eo',
            status_user: 3
          })
        }} style={applyStyle({ width: (LibStyle.width - 40) * 0.5, borderWidth: 2, borderColor: LibStyle.colorGreen, height: 40, borderRadius: 16, backgroundColor: LibStyle.colorGreen, flexDirection: 'row-reverse', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
          <LibIcon size={18} color={'white'} name="qrcode" style={applyStyle({ fontWeight: 'bold', transform: [{ rotate: '180deg' }] })} />
          <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: 'white', marginRight: 10 })} >{esp.lang("event/counter_cashier_sell", "scan_again")}</Text>
        </TouchableOpacity>
      </View>
    </View>
  )
}