// withHooks

import { EventFirebase_socket, EventFirebase_socketProperty } from 'esoftplay/cache/event/firebase_socket/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import { useTimeout } from 'esoftplay/timeout';
import { useKeepAwake } from 'expo-keep-awake';
import LottieView from 'lottie-react-native';
import React, { useEffect, useRef } from 'react';
import { Text, View } from 'react-native';

export interface EventQueueArgs {

}
export interface EventQueueProps {
  event_id: number,
  type: 1 | 2,
  onDone?: () => void
}

let timer: any;
function debounce(func: Function, timeout: number): any {
  clearTimeout(timer);
  timer = setTimeout(() => { func() }, timeout);
  return timer;
}

const EVENT_PRICING_QUEUE = 'event_pricing_queue'

const pricing_queue = useGlobalState<any>({})

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


const queueNumberState = useGlobalState(1)
export default function m(props: EventQueueProps): any {
  const counter = useRef<number>(0)
  const { addQueue, getQueue, updateQueueExp, doneQueue } = EventFirebase_socket()
  const [queueStatus, setQueueStatus] = useSafeState(0)
  let { event_id, autoPass } = LibNavigation.getArgsAll<any>(props, props)
  event_id = String(event_id)
  const [number, setNumber, getNumber] = useSafeState(esp.lang("event/queue_pricing", "info"))
  const animation = useRef<LottieView>(null)
  let refTimeout = useRef<any>()
  const pathQueue = EVENT_PRICING_QUEUE

  const timeout = useTimeout()
  useKeepAwake()

  useEffect(() => {
    setQueueStatus(1)
    addQueue(String(pathQueue), String(event_id), () => {
      getCurrentQueue(1)
    });
    timeout(() => {
      animation.current?.play()
    }, 300);
    return () => {
      queueNumberState.reset()
      clearTimeout(timer)
      clearTimeout(refTimeout.current)
      LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
    }
  }, [])

  useEffect(() => {
    if (queueStatus == 2) {
      clearTimeout(refTimeout.current)
    } else {
      clearTimeout(refTimeout.current)
      refTimeout.current = setTimeout(() => {
        LibNavigation.replace('event/queue_pricing', { event_id, autoPass })
      }, 10000);
    }
  }, [queueStatus])

  function getCurrentQueue(timeout?: number) {
    debounce(() => {
      const limit = EventFirebase_socketProperty?.eventQueueConfig?.get(event_id)?.limit
      getQueue(pathQueue, event_id, 60000, (idx, key) => {
        counter.current++
        if (limit == 0) {
          LibNavigation.sendBackResult(1, LibNavigation.getResultKey(props))
        } else
          if (idx < limit) {
            updateQueueExp(pathQueue, event_id)
            setNumber(esp.lang("event/queue_pricing", "info2"))
            pricing_queue.set({ pathQueue, event_id, key })
            clearTimeout(refTimeout.current)
            clearTimeout(timer)
            if (autoPass) {
              doneQueue(pathQueue, event_id, key, () => { })
            }
            LibNavigation.sendBackResult(1, LibNavigation.getResultKey(props))
          } else {
            setQueueStatus(2)
            queueNumberState.set((idx + 1) - limit)
            const updatedCount = (idx + 1) - limit
            if (isNaN(Number(getNumber())) || updatedCount < Number(getNumber()))
              setNumber(String((updatedCount).toFixed(0)))
          }
      })
      getCurrentQueue(Math.max(Math.min((queueNumberState.get() / limit) * 1000, 6000), 3000));
    }, timeout || 3000)
  }

  return (
    <View style={{ flex: 1, backgroundColor: 'white', justifyContent: 'center', alignItems: 'center' }} >
      <View style={{ alignItems: 'center' }} >
        <LottieView
          ref={animation}
          loop={true}
          style={{ width: 150, height: 150 }}
          source={esp.assets('pending.json')}
        />
      </View>
      {/* {esp.isDebug("timer debug") ? <EventTimer /> : null} */}
      {
        Number(number) > 0 ?
          <>
            <Text style={{ textAlign: 'center', margin: 16, fontSize: 20 }} >{esp.lang("event/queue_pricing", "wait")}</Text>
            <Text style={{ fontSize: 50, textAlign: 'center', margin: 24, fontWeight: 'bold' }}>{LibUtils.number(number)}</Text>
            <View style={{ backgroundColor: LibUtils.hexToRgba(LibStyle.colorPrimary, 0.05), padding: 15, alignItems: 'center', margin: 16, borderRadius: 5, borderWidth: 1, borderColor: LibUtils.hexToRgba(LibStyle.colorPrimary, 0.5) }} >
              <Text style={{ fontSize: 18, textAlign: 'center' }} >{esp.lang("event/queue_pricing", "number")}</Text>
            </View>
            <Text style={{ textAlign: 'center', margin: 16, fontSize: 20 }} >{esp.lang("event/queue_pricing", "dont_go")}</Text>
          </>
          :
          <>
            <Text style={{ fontSize: 20, textAlign: 'center', margin: 24 }}>{number}</Text>
          </>
      }
    </View>
  )
}