// withHooks

import { EventExchange_ticket_resultProperty } from 'esoftplay/cache/event/exchange_ticket_result/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/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 { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { UseTasks } from 'esoftplay/cache/use/tasks/import';
import esp from 'esoftplay/esp';
import useGlobalState from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import useGlobalSubscriber, { useGlobalSubscriberReturn } from 'esoftplay/subscribe';
import { useTimeout } from 'esoftplay/timeout';
import React, { useEffect, useRef } from 'react';
import isEqual from 'react-fast-compare';
import { Pressable, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventExchange_ticketArgs {

}
export interface EventExchange_ticketProps {

}


// new
export const stateExchangeLog = useGlobalState({}, {
  persistKey: 'event/exchange_ticket_log',
  inFile: true,
  loadOnInit: true
})

function addCounter(counter: number, type: string) {
  const cdate = LibUtils.moment().localeFormat('YYYY-MM-DD HH')
  stateExchangeLog.set((old: any) => {
    if (!old[type]) { old[type] = {} }
    return LibObject.update(old, (c) => (c || 0) + counter)(type, cdate)
  })
}

export function getDataByDate(): any {
  return stateExchangeLog.get()
}

export function addCounterScan(counter: number) {
  addCounter(counter, 'scan')
}
export function addCounterScanNo(counter: number) {
  addCounter(counter, 'scan_failed')
}
export function addCounterSend(counter: number) {
  addCounter(counter, 'send')
}
export function addCounterResponseOK(counter: number) {
  addCounter(counter, 'api_ok')
}
export function addCounterResponseNo(counter: number) {
  addCounter(counter, 'api_no')
}
export function addCounterResponseTimeout(counter: number) {
  addCounter(counter, 'timeout')
}
export function addCounterGiftBy(title: string, counter: number) {
  addCounter(counter, `gift_${title}`)
}

const subscriber = useGlobalSubscriber()
export function subscribeSync(): useGlobalSubscriberReturn {
  return subscriber
}

const useTasks1 = UseTasks()

export default function m(props: EventExchange_ticketProps): any {
  const { dataEvent }: any = LibNavigation.getArgsAll(props)
  const dialogInput = useRef<LibSlidingup>(null)

  const [dataConfig, setDataConfig] = useSafeState<any>()
  const [error, setError] = useSafeState<string>()
  const [refreshing, setRefreshing] = useSafeState<boolean>(false);

  let inputAccessCode = React.useRef<EventInput_rectangle>(null)

  const timeoutSync = useRef<any>()
  const timeout = useTimeout()
  const [syncTicketExchange] = useTasks1((item: any) => new Promise((next) => {
    clearTimeout?.(timeoutSync.current)
    timeoutSync.current = timeout(() => {
      next()
    }, 10000);
    new LibCurl(item?.url, item?.post, (res, msg) => {
      addCounterResponseOK(1)
      let a = EventExchange_ticket_resultProperty.stateListConfirm().get().filter((x: any) => !isEqual(item, x))
      EventExchange_ticket_resultProperty.stateListConfirm().set(a)
      next()
    }, (err) => {
      addCounterResponseNo(1)
      next()
    })
  }))

  subscriber.useSubscribe(() => {
    syncTicketExchange(subscriber.getValue())
  })

  useEffect(() => {
    subscriber.trigger(EventExchange_ticket_resultProperty.stateListConfirm().get())
    loadDataConfig()
  }, [])


  function loadDataConfig() {
    new LibCurl('event_booking_exchange_config?event_id=' + dataEvent?.id, null, (res, msg) => {
      setDataConfig(res)
      setRefreshing(false)
    }, (err) => {
      setRefreshing(false)
      setError(err?.message)
      // LibToastProperty.show(err?.message)
    }, 1)
  }

  function doSubmit() {
    inputAccessCode.current?.blur()
    if (inputAccessCode.current?.getText() == '') {
      LibToastProperty.show(esp.lang("event/visitor_index", "alert_error_not_empty_code"))
      inputAccessCode.current?.focus()
      return
    }
    dialogInput.current?.hide()
    LibNavigation.navigate('event/exchange_ticket_result', { event_title: dataEvent?.name, event_id: dataEvent?.id, qr: inputAccessCode.current?.getText().toUpperCase() })
  }

  function onRefresh() {
    setRefreshing(true)
    loadDataConfig()
  }


  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/exchange_ticket", "header")} subtitle={dataEvent?.name} />
      <ScrollView style={{ flex: 1 }} refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}>
        <Pressable onPress={() => {
          LibNavigation.navigate('event/exchange_ticket_list')
        }} style={{ margin: 15, marginBottom: 0, padding: 10, borderWidth: 1, backgroundColor: '#fff', borderColor: LibStyle.colorRed, flex: 1, borderRadius: 10, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
          <Text allowFontScaling={false}>{esp.lang("event/exchange_ticket", "exchange_history")}</Text>
          <LibIcon name='chevron-right' />
        </Pressable >
        <View style={{ flex: 1, margin: 15, backgroundColor: '#fff', borderRadius: 10, ...LibStyle.elevation(2) }}>
          <TouchableOpacity onPress={() => {
            if (dataConfig) {
              LibNavigation.navigate('component/scanner', { event_title: dataEvent?.name, event_id: dataEvent?.id, fromPage: "event/exchange_ticket" })
            }
          }}>
            <View style={{ width: LibStyle.width - 30, overflow: 'hidden', borderTopLeftRadius: 10, borderTopRightRadius: 10, height: LibStyle.height * 0.5, backgroundColor: '#b8b7bf', justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
              <LibPicture source={esp.assets('icons/ic_barcode_white.png')} style={{ height: 250, width: 250 }} />
              <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", marginTop: 10, color: '#fff' }}>{esp.lang("transfer/index", "klik_here")}</Text>
            </View>
          </TouchableOpacity>

          {
            (dataConfig || error) ?
              <View style={{ marginTop: 20, margin: 10 }}>
                {
                  dataConfig &&
                  <Text allowFontScaling={false} style={{ fontFamily: 'MonoSpace', letterSpacing: 1 }}>{esp.lang("event/exchange_ticket", "type_can_scan")}</Text>
                }

                {
                  dataConfig && dataConfig?.map((item: any, i: number) => {
                    return (
                      <Text key={i} allowFontScaling={false} style={{ marginTop: 4, fontFamily: 'MonoSpace', letterSpacing: 1 }}>{(i + 1) + "."} {item?.type}</Text>
                    )
                  })
                }
                {
                  error &&
                  <Text allowFontScaling={false} style={{ color: LibStyle.colorRed, fontWeight: 'bold', fontFamily: 'MonoSpace', letterSpacing: 1 }}>{error}</Text>
                }
              </View>
              :
              <View style={{ marginTop: 30, marginBottom: 20 }}>
                <LibLoading />
              </View>
          }

        </View >
      </ScrollView>

      <Pressable onPress={() => {
        if (dataConfig) {
          dialogInput.current?.show()
        }
      }} style={{ ...LibStyle.elevation(2), alignContent: 'center', alignItems: 'center', justifyContent: 'center', position: 'absolute', width: 50, height: 50, borderRadius: 25, backgroundColor: LibStyle.colorRed, bottom: 20, right: 15 }}>
        <LibIcon.Ionicons name='terminal-outline' color='#fff' />
      </Pressable>

      <LibSlidingup ref={dialogInput}>
        <View style={{ backgroundColor: '#f6f6f6', borderTopRightRadius: 20, borderTopLeftRadius: 20, paddingHorizontal: 19, }}>
          <Text allowFontScaling={false} style={{ marginTop: 26, marginBottom: 23, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, textAlign: "center", color: "#34495e" }}>{esp.lang("event/exchange_ticket", "input_qr")}</Text>
          <EventInput_rectangle
            ref={inputAccessCode}
            onSubmitEditing={() => doSubmit()}
            blurOnSubmit
            returnKeyType="done"
            autoCapitalize='characters'
            style={{ borderColor: '#c4c4c4', height: 35, margin: 15, borderRadius: 5 }}
            placeholder={esp.lang("event/exchange_ticket", "placeholder_code")}
          />

          <TouchableOpacity onPress={() => { doSubmit() }}>
            <View style={{ margin: 15, marginTop: 20, height: 35, borderRadius: 5, backgroundColor: "#6c432c", justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 }} >
              <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, textAlign: "center", textAlignVertical: 'center', color: 'white', marginRight: 13, marginLeft: 10 }} >{esp.lang("event/visitor_index", "submit")}</Text>
            </View>
          </TouchableOpacity>

        </View>
      </LibSlidingup>


    </View>
  )
}