// withHooks
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventTms_in_successProperty } from 'esoftplay/cache/event/tms_in_success/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibFocus } from 'esoftplay/cache/lib/focus/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 { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { UseTasks } from 'esoftplay/cache/use/tasks/import';
import { UserClass } from 'esoftplay/cache/user/class/import';
import { reportApiError } from 'esoftplay/error';
import moment from 'esoftplay/moment';
import useGlobalSubscriber, { useGlobalSubscriberReturn } from 'esoftplay/subscribe';


import { applyStyle } from 'esoftplay';
import { EventTms_in_hall_successProperty } from 'esoftplay/cache/event/tms_in_hall_success/import';
import { EventTms_out_hall_successProperty } from 'esoftplay/cache/event/tms_out_hall_success/import';
import { EventTms_out_successProperty } from 'esoftplay/cache/event/tms_out_success/import';
import esp from 'esoftplay/esp';
import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import { useTimeout } from 'esoftplay/timeout';
import React, { useEffect, useRef } from 'react';
import isEqual from 'react-fast-compare';
import { Image, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';

export interface EventTms_homeArgs {

}
export interface EventTms_homeProps {

}

const stateIsDirect = useGlobalState<boolean>(true)

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

const stateCounter = useGlobalState({}, {
  persistKey: 'event/tms_home_scan_counter',
  loadOnInit: true
})

export function counterState(): useGlobalReturn<any> {
  return stateCounter
}

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

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

// {
//   scan: {
//       2219: {
//        2024-01 - 20: 1
//       }
//   }
// }

// counter entrance
export function addCounterEntranceScan(counter: number, price_id: string) {
  addCounter(counter, 'entrance_scan', price_id)
}
export function addCounterEntranceScanFailed(counter: number, price_id: string) {
  addCounter(counter, 'entrance_scan_failed', price_id)
}
export function addCounterEntranceOpenGate(counter: number, price_id: string) {
  addCounter(counter, 'entrance_opengate', price_id)
}
export function addCounterEntranceOpenGateIdCard(counter: number, price_id: string) {
  addCounter(counter, 'entrance_opengate_idcard', price_id)
}
export function addCounterEntranceSend(counter: number, price_id: string) {
  addCounter(counter, 'entrance_send', price_id)
}
export function addCounterEntranceOk(counter: number, price_id: string) {
  addCounter(counter, 'entrance_api_ok', price_id)
}
export function addCounterEntranceNo(counter: number, price_id: string) {
  addCounter(counter, 'entrance_api_no', price_id)
}
export function addCounterEntranceTicket(counter: number, price_id: string) {
  addCounter(counter, 'entrance_ticket', price_id)
}
export function addCounterEntranceTimeout(counter: number, price_id: string) {
  addCounter(counter, 'entrance_timeout', price_id)
}

// counter exit
export function addCounterOutScan(counter: number, price_id: string) {
  addCounter(counter, 'out_scan', price_id)
}
export function addCounterOutTicket(counter: number, price_id: string) {
  addCounter(counter, 'out_ticket', price_id)
}
export function addCounterOutScanFailed(counter: number, price_id: string) {
  addCounter(counter, 'out_scan_failed', price_id)
}
export function addCounterOutOpenGate(counter: number, price_id: string) {
  addCounter(counter, 'out_opengate', price_id)
}
export function addCounterOutSend(counter: number, price_id: string) {
  addCounter(counter, 'out_send', price_id)
}
export function addCounterOutOK(counter: number, price_id: string) {
  addCounter(counter, 'out_api_ok', price_id)
}
export function addCounterOutNO(counter: number, price_id: string) {
  addCounter(counter, 'out_api_no', price_id)
}


// hall in
export function addCounterHallInScan(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_scan', price_id)
}
export function addCounterHallInScanFailed(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_scan_failed', price_id)
}
export function addCounterHallInTicket(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_ticket', price_id)
}
export function addCounterHallInGate(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_opengate', price_id)
}
export function addCounterHallInGateIdcard(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_opengate_idcard', price_id)
}
export function addCounterHallInSend(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_send', price_id)
}
export function addCounterHallInOK(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_api_ok', price_id)
}
export function addCounterHallInNO(counter: number, price_id: string) {
  addCounter(counter, 'hall_in_api_no', price_id)
}


// hall out
export function addCounterHallOutScan(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_scan', price_id)
}
export function addCounterHallOutScanFailed(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_scan_failed', price_id)
}
export function addCounterHallOutTicket(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_ticket', price_id)
}
export function addCounterHallOutOpenGate(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_opengate', price_id)
}
export function addCounterHallOutOpenGateIdCard(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_opengate_idcard', price_id)
}
export function addCounterHallOutSend(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_send', price_id)
}
export function addCounterHallOutOK(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_api_ok', price_id)
}
export function addCounterHallOutNO(counter: number, price_id: string) {
  addCounter(counter, 'hall_out_api_no', price_id)
}


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

const subscriberReset = useGlobalSubscriber()
export function subscribeSyncReset(): useGlobalSubscriberReturn {
  return subscriberReset
}

const subscriberExit = useGlobalSubscriber()
export function subscribeSyncExit(): useGlobalSubscriberReturn {
  return subscriberExit
}

const subscriberExitReset = useGlobalSubscriber()
export function subscribeSyncExitReset(): useGlobalSubscriberReturn {
  return subscriberExitReset
}

const subscriberHallIn = useGlobalSubscriber()
export function subscribeSyncHallIn(): useGlobalSubscriberReturn {
  return subscriberHallIn
}

const subscriberHallInReset = useGlobalSubscriber()
export function subscribeSyncHallInReset(): useGlobalSubscriberReturn {
  return subscriberHallInReset
}

const subscriberHallOut = useGlobalSubscriber()
export function subscribeSyncHallOut(): useGlobalSubscriberReturn {
  return subscriberHallOut
}

const subscriberHallOutReset = useGlobalSubscriber()
export function subscribeSyncHallOutReset(): useGlobalSubscriberReturn {
  return subscriberHallOutReset
}

const useTasks = UseTasks()
const useTasksExit = UseTasks()
const useTasksHallIn = UseTasks()
const useTasksHallOut = UseTasks()
export default function m(props: EventTms_homeProps): any {
  const { is_scanner, selectedGate, typeScanner }: any = LibNavigation.getArgsAll(props)

  // esp.log(counterState().get());

  const timeoutSync = useRef<any>()
  const timeout = useTimeout()
  const [syncUseTicket, resetSyncUseTicket] = useTasks((item: any) => new Promise((next) => {
    const [url, post] = item;
    let _post = LibObject.assign({}, post)()
    clearTimeout?.(timeoutSync.current)
    timeoutSync.current = timeout(() => {
      addCounterEntranceTimeout(1, _post?.price_id)
      next()
    }, 30000);
    addCounterEntranceSend(1, _post?.price_id)
    _post["trx_id"] = new Date().getTime() + "" + UserClass.state().get()?.id;

    new LibCurl(url, _post, (res, msg) => {
      EventTms_in_successProperty.syncUsedTiket().set((old) => old.filter((x) => !isEqual([url, post], x)))
      addCounterEntranceOk(1, _post?.price_id)
      addCounterEntranceTicket(post?.qty, _post?.price_id)
      next()
    }, (err: any) => {
      addCounterEntranceNo(1, _post?.price_id)
      reportApiError(url, JSON.stringify({ post, response: err }))
      next()
    }, 1)

  }), () => {

  })

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

  subscriberReset.useSubscribe(() => {
    resetSyncUseTicket()
    syncUseTicket(subscriberReset.getValue())
  })


  const [syncTicketExit, resetSyncTicketExit] = useTasksExit((item: any) => new Promise((next) => {
    const [url, post] = item;
    let _post = LibObject.assign({}, post)()
    addCounterOutSend(1, _post?.price_id?.[0])
    _post["trx_id"] = new Date().getTime() + "" + UserClass.state().get()?.id;
    new LibCurl(url, _post, (res, msg) => {
      EventTms_out_successProperty.syncTicketExit().set((old) => old.filter((x) => !isEqual([url, post], x)))
      _post?.price_id?.map((x: any) => {
        addCounterOutTicket(1, x)
      })
      next()
      addCounterOutOK(1, _post?.price_id?.[0])
    }, (err) => {
      addCounterOutNO(1, _post?.price_id?.[0])
      reportApiError(url, JSON.stringify({ post, response: err }))
      next()
    }, 1)
  }), () => {

  })

  subscriberExit.useSubscribe(() => {
    syncTicketExit(subscriberExit.getValue())
  })

  subscriberExitReset.useSubscribe(() => {
    resetSyncTicketExit()
    syncTicketExit(subscriberExitReset.getValue())
  })

  const [syncTicketHallIn, resetSyncTicketHallIn] = useTasksHallIn((item: any) => new Promise((next) => {
    const [url, post] = item;
    let _post = LibObject.assign({}, post)()
    addCounterHallInSend(1, _post?.price_id?.[0])
    _post["trx_id"] = new Date().getTime() + "" + UserClass.state().get()?.id;
    new LibCurl(url, _post, (res, msg) => {
      EventTms_in_hall_successProperty.syncHallIn().set((old) => old.filter((x) => !isEqual([url, post], x)))
      _post?.price_id?.map((x: any) => {
        addCounterHallInTicket(1, x)
      })
      next()
      addCounterHallInOK(1, _post?.price_id?.[0])
    }, (err) => {
      addCounterHallInNO(1, _post?.price_id?.[0])
      reportApiError(url, JSON.stringify({ post, response: err }))
      next()
    }, 1)
  }), () => {

  })

  subscriberHallIn.useSubscribe(() => {
    syncTicketHallIn(subscriberHallIn.getValue())
  })

  subscriberHallInReset.useSubscribe(() => {
    resetSyncTicketHallIn()
    syncTicketHallIn(subscriberHallInReset.getValue())
  })

  const [syncTicketHallOut, resetSyncTicketHallOut] = useTasksHallOut((item: any) => new Promise((next) => {
    const [url, post] = item;
    let _post = LibObject.assign({}, post)()
    addCounterHallOutSend(1, _post?.price_id?.[0])
    _post["trx_id"] = new Date().getTime() + "" + UserClass.state().get()?.id;
    new LibCurl(url, _post, (res, msg) => {
      EventTms_out_hall_successProperty.syncHallOut().set((old) => old.filter((x) => !isEqual([url, post], x)))
      _post?.price_id?.map((x: any) => {
        addCounterHallOutTicket(1, x)
      })
      next()
      addCounterHallOutOK(1, _post?.price_id?.[0])
    }, (err) => {
      addCounterHallOutNO(1, _post?.price_id?.[0])
      reportApiError(url, JSON.stringify({ post, response: err }))
      next()
    }, 1)
  }), () => {

  })

  subscriberHallOut.useSubscribe(() => {
    syncTicketHallOut(subscriberHallOut.getValue())
  })

  subscriberHallOutReset.useSubscribe(() => {
    resetSyncTicketHallOut()
    syncTicketHallOut(subscriberHallOutReset.getValue())
  })


  const [result, setResult] = useSafeState<any>(null)
  const [resultTypeTicket, setResultTypeTicket] = useSafeState<any>(null)
  const [resultConfigPriority, setResultConfigPriority] = useSafeState<any>(null)
  const [refreshing, setRefreshing] = useSafeState<boolean>(false);

  const date = LibUtils.moment().localeFormat('YYYY-MM-DD HH:mm:ss')

  useEffect(() => {
    resetSyncUseTicket()
    resetSyncTicketExit()
    resetSyncTicketHallIn()
    resetSyncTicketHallOut()

    loadData()
    loadDataTypeTicket()
    loadDataConfigPriority()
  }, [])

  function loadDataTypeTicket() {
    new LibCurl('event_tms_ticket_type?event_id=' + is_scanner?.id, null, (res, msg) => {
      setRefreshing(false)
      setResultTypeTicket(res)
    }, (error) => {
      LibDialog.warning(esp.lang("event/tms_home", "warning_load"), error?.message)
      LibNavigation.back()
      setRefreshing(false)
    })
  }

  function loadData() {
    subscriber.trigger(EventTms_in_successProperty.syncUsedTiket().get())
    new LibCurl('event_tms_visitor?event_id=' + is_scanner?.id, null, (res, msg) => {
      setResult(res)
      setRefreshing(false)
    }, (error) => {
      LibDialog.warning(esp.lang("event/tms_home", "warning_load"), error?.message)
      LibNavigation.back()
      setRefreshing(false)
    })
  }

  function loadDataConfigPriority() {
    new LibCurl('event_tms_access_price?event_id=' + is_scanner?.id, null, (res, msg) => {
      setResultConfigPriority(res)
      setRefreshing(false)
    }, (error) => {
      setRefreshing(false)
    })
  }

  function onRefresh() {
    setRefreshing(true)
    loadData()
    loadDataTypeTicket()
    loadDataConfigPriority()
  }

  if (!result) {
    return <LibLoading />
  }

  let tmsPercentage = result?.total_quota_visitor == 0 && result?.total_visitor == 0 ? 0 : result?.total_visitor > 0 && result?.total_quota_visitor == 0 ? 5 : (result?.total_visitor / result?.total_quota_visitor) * 100
  let hallPercentage = result?.total_hall_quota_visitor == 0 && result?.total_hall_visitor == 0 ? 0 : result?.total_hall_visitor > 0 && result?.total_hall_quota_visitor == 0 ? 5 : (result?.total_hall_visitor / result?.total_hall_quota_visitor) * 100
  let mainPercentage = typeScanner == "tms" ? tmsPercentage : hallPercentage
  let twentyFive = 100 / 4
  let fifty = 100 / 2
  let seventyFive = 100 * 0.75

  let args = {
    event_title: is_scanner?.name,
    event_id: is_scanner?.id,
    selectGate: selectedGate,
    typeScanner: typeScanner,
    configPriority: resultConfigPriority
  }

  function setColorProg(percentage: number) {
    if (percentage <= 100 && percentage > seventyFive) {
      return "#3399FF"
    } else if (percentage <= seventyFive && percentage > fifty) {
      return "#3399FF"
    } else if (percentage <= fifty && percentage > twentyFive) {
      return "#3399FF"
    } else {
      return "#3399FF"
    }
  }

  function renderViewTms(item: any, i: number) {
    let percentages = item?.quota_visitor == 0 && item?.visitor == 0 ? 0 : item?.visitor > 0 && item?.quota_visitor == 0 ? 5 : (item?.visitor / item?.quota_visitor) * 100
    return (
      <View key={i} style={applyStyle({ marginLeft: 7, marginRight: 7, marginBottom: 10, borderRadius: 10, borderWidth: 2, padding: 10, borderColor: "#f1f1f1" })}>
        {progressBar(percentages, 'small')}
        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 8 }} >
          <Text allowFontScaling={false} style={applyStyle({ textAlign: 'left', fontSize: 14, color: '#000', fontWeight: 'bold', marginRight: 10, flex: 1 })}>{item.type}</Text>
          <Text allowFontScaling={false} style={applyStyle({ textAlign: 'right', fontSize: 14, fontWeight: 'bold' })}>{item.quota_visitor == "0" ? item?.visitor : item?.visitor + "/" + item.quota_visitor}</Text>
        </View>
      </View>
    )
  }

  function renderViewHall(item: any, i: number) {
    let percentages = item?.quota_visitor == 0 && item?.visitor == 0 ? 0 : item?.visitor > 0 && item?.quota_visitor == 0 ? 5 : (item?.visitor / item?.quota_visitor) * 100
    return (
      <View key={i} style={applyStyle({ marginLeft: 7, marginRight: 7, marginBottom: 10, borderRadius: 10, borderWidth: 2, padding: 10, borderColor: "#f1f1f1" })}>
        {/* <ComponentCircural_progress size={60} strokeWidth={7} percentage={percentages} color={setColorProg(percentages)} /> */}
        {progressBar(percentages, 'small')}
        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 8 }} >
          <Text allowFontScaling={false} style={applyStyle({ textAlign: 'left', fontSize: 14, color: '#000', fontWeight: 'bold', marginRight: 10, flex: 1 })}>{item.name}</Text>
          <Text allowFontScaling={false} style={applyStyle({ textAlign: 'right', fontSize: 14, fontWeight: 'bold' })}>{item.quota_visitor == "0" ? item?.visitor : item?.visitor + "/" + item.quota_visitor}</Text>
        </View>
      </View>
    )
  }


  function progressBar(percentage: number, size: 'small' | 'large') {
    if (percentage < 0) {
      percentage = 0
    }
    return (
      <View style={{ width: LibStyle.width - 60, height: size == 'small' ? 10 : 20, borderRadius: 10, backgroundColor: '#f1f2f3' }} >
        <View style={{ flex: 1, borderRadius: 10, width: (LibStyle.width - 60) * (percentage / 100), backgroundColor: setColorProg(percentage) }} />
      </View>
    )
  }

  return (
    <View style={applyStyle({ flex: 1, backgroundColor: '#fff' })}>
      <LibFocus onFocus={loadData} />
      <EventHeader title={esp.lang("event/tms_home", "visitor_info")} subtitle={typeScanner == "tms" ? esp.lang("event/tms_home", "header_title1", is_scanner?.name) : esp.lang("event/tms_home", "header_title2", is_scanner?.name)} />
      <View style={{ margin: 15, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
        {
          <TouchableOpacity onPress={() => {
            LibNavigation.navigate('event/tms_log', {
              event_id: is_scanner?.id,
              gate: selectedGate
            })
          }} style={{ padding: 10, backgroundColor: "#000", borderRadius: 10, ...LibStyle.elevation(2) }}>
            <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: '#fff' })} >{esp.lang("event/tms_home", "tms_close")}</Text>
          </TouchableOpacity>
        }

        <View style={{ justifyContent: 'flex-end', flexDirection: 'row', alignContent: 'center', alignItems: 'center', flex: 1 }}>
          <TouchableOpacity onPress={() => { LibDialog.info(esp.lang("user/menu_bigbank", "title_info_bbo_wallet"), esp.lang("event/tms_home", "info_msg")) }} style={{ marginRight: 10 }}>
            <LibIcon name="information-outline" />
          </TouchableOpacity>
          <TouchableOpacity onPress={() => {
            LibNavigation.navigate('event/tms_check_code', {
              event_id: is_scanner?.id,
              gate: selectedGate
            })
          }} style={{ padding: 10, marginRight: 0, backgroundColor: LibStyle.colorRed, borderRadius: 10, ...LibStyle.elevation(2) }}>
            <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: '#fff' })} >{esp.lang("event/tms_home", "check_code")}</Text>
          </TouchableOpacity>
        </View>
      </View>
      {/* <UseCondition if={dataScan.length > 0}>
        <Pressable
          style={{ flexDirection: 'row', paddingHorizontal: 17, alignItems: 'center' }}
          onPress={() => syncUseTicket(EventTms_in_successProperty.syncUsedTiket().get())} >
          <LibIcon name='sync' />
          <Text>{"Menyinkronkan data, " + dataScan.length + " data tersisa.."}</Text>
        </Pressable>
      </UseCondition> */}
      {
        result?.event?.config?.jumbotron_app != 0 ?
          <ScrollView refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}>
            <View style={applyStyle({ margin: 15, padding: 5 })}>
              <View style={applyStyle({ borderRadius: 10, padding: 10, borderColor: "#f1f1f1", backgroundColor: LibUtils.hexToRgba(LibStyle.colorPrimary, 0.5) })}>
                {progressBar(mainPercentage, 'large')}
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }} >
                  <Text allowFontScaling={false} style={applyStyle({ margin: 10, textAlign: 'center', fontSize: 20, marginBottom: 20, fontWeight: 'bold', color: '#000' })}>{esp.lang("event/tms_home", "title")}</Text>
                  {
                    typeScanner == "tms" ?
                      <Text allowFontScaling={false} style={applyStyle({ marginRight: 10, textAlign: 'center', fontSize: 25, fontWeight: 'bold', color: '#000' })}>{result.total_quota_visitor == 0 ? result?.total_visitor : result?.total_visitor + "/" + result.total_quota_visitor}</Text>
                      :
                      <Text allowFontScaling={false} style={applyStyle({ marginRight: 10, textAlign: 'center', fontSize: 25, fontWeight: 'bold', color: '#000' })}>{result.total_hall_quota_visitor == 0 ? result?.total_hall_visitor : result?.total_hall_visitor + "/" + result.total_hall_quota_visitor}</Text>
                  }
                </View>
              </View>
              <View style={applyStyle({ flexWrap: 'wrap', marginTop: 10, flexDirection: 'row', justifyContent: 'space-evenly' })}>
                {
                  typeScanner == "tms" ?
                    result?.prices?.map(renderViewTms)
                    :
                    result?.halls?.map(renderViewHall)
                }
              </View>
            </View>
          </ScrollView >
          :
          <Image source={{ uri: 'https://static.vecteezy.com/system/resources/previews/005/594/108/non_2x/mobile-application-for-scanning-qr-code-hand-holding-smartphone-scan-qr-code-icon-phone-app-barcode-scanner-vector.jpg' }} style={{ flex: 1, opacity: 0.3, resizeMode: 'cover' }} />
      }

      <View style={applyStyle({ padding: 15, paddingVertical: 5, backgroundColor: '#fff', ...LibStyle.elevation(2) })}>
        <View style={applyStyle({ flexDirection: 'row', marginBottom: 8, alignContent: 'center', alignItems: 'center' })}>
          <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#999' })}>{typeScanner == "tms" ? esp.lang("event/tms_home", "type1") : esp.lang("event/tms_home", "type2")} </Text>
          <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorPrimary })}>{selectedGate?.name}</Text>
        </View>

        {
          LibUtils.moment(result?.event?.start_scan).serverFormat('YYYY-MM-DD HH:mm:ss') <= date ?
            <>
              <View style={applyStyle({ flexDirection: 'row', justifyContent: 'space-between', })}>
                <TouchableOpacity onPress={() => {
                  LibNavigation.navigate('component/scanner', {
                    fromPage: 'event/tms_home',
                    scan_type: typeScanner == "tms" ? 'exit' : 'hall_out',
                    gate_type: 0, // ini kalo 0 itu out
                    price_type: resultTypeTicket, // ini digunakan di event/tms_in
                    ...args
                  })

                }} style={applyStyle({ width: (LibStyle.width - 40) * 0.5, borderWidth: 1, borderColor: 'rgba(0, 0, 0, 0)', height: 40, borderRadius: 16, backgroundColor: LibStyle.colorRed, flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
                  <LibIcon size={18} color="#fff" name="logout" style={applyStyle({ transform: [{ rotate: '180deg' }] })} />
                  <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: '#fff', marginLeft: 15 })} >{esp.lang("event/tms_home", "exit")}</Text>
                </TouchableOpacity>

                <TouchableOpacity onPress={() => {
                  // if (esp.isDebug("") && UserClass?.state().get().email == "bagus@fisip.net") {
                  //   LibNavigation.navigate('tms/gate_in')
                  // } else {
                  LibNavigation.navigate('component/scanner', {
                    fromPage: 'event/tms_home',
                    scan_type: typeScanner == "tms" ? 'entrance' : 'hall_in',
                    gate_type: 1, // ini kalo 1 itu in
                    price_type: resultTypeTicket,
                    url_ticket_detail: result?.url_ticket_detail,
                    url_ticket_update: result?.url_ticket_update,
                    ...args
                  })
                  // }
                }} style={applyStyle({ width: (LibStyle.width - 40) * 0.5, borderWidth: 1, borderColor: 'rgba(0, 0, 0, 0)', height: 40, borderRadius: 16, backgroundColor: LibStyle.colorGreen, flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
                  <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: '#fff', marginRight: 15 })} >{esp.lang("event/tms_home", "entrance")}</Text>
                  <LibIcon size={18} color="#fff" name="login" />
                </TouchableOpacity>
              </View>
              {
                typeScanner == "tms" && result?.event?.config?.temporary_out == 1 &&
                <View style={{ marginTop: 10, flexDirection: 'row', justifyContent: 'space-between' }}>
                  <TouchableOpacity onPress={() => {
                    LibNavigation.navigate('component/scanner', {
                      fromPage: 'event/tms_home',
                      scan_type: 'exit_temporary',
                      ...args
                    })
                  }} style={applyStyle({ width: (LibStyle.width - 40) * 0.5, borderWidth: 2, borderColor: LibStyle.colorRed, height: 40, borderRadius: 16, backgroundColor: "#fff", flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
                    <LibIcon size={18} color={LibStyle.colorRed} name="logout" style={applyStyle({ fontWeight: 'bold', transform: [{ rotate: '180deg' }] })} />
                    <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: LibStyle.colorRed, marginLeft: 10 })} >{esp.lang("event/tms_home", "temp_out")}</Text>
                  </TouchableOpacity>
                  <TouchableOpacity onPress={() => {
                    // LibNavigation.navigate('event/tms_in_again')
                    LibNavigation.navigate('component/scanner', {
                      fromPage: 'event/tms_home',
                      gate_type: 1,
                      scan_type: 'entrance_again',
                      price_type: resultTypeTicket,
                      url_ticket_detail: result?.url_ticket_detail,
                      url_ticket_update: result?.url_ticket_update,
                      ...args
                    })
                  }} style={applyStyle({ width: (LibStyle.width - 40) * 0.5, borderWidth: 2, borderColor: LibStyle.colorGreen, height: 40, borderRadius: 16, backgroundColor: 'white', flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
                    <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: LibStyle.colorGreen, marginRight: 15 })} >{esp.lang("event/tms_home", "re_in")}</Text>
                    <LibIcon size={18} color={LibStyle.colorGreen} name="login" />
                  </TouchableOpacity>
                </View>
              }
            </>
            :
            <View style={{ padding: 10, backgroundColor: "#C3BEBE", borderRadius: 10, borderStyle: 'dashed' }}>
              <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, textAlign: "center", textAlignVertical: 'center', color: '#000', marginHorizontal: 10 }} >{esp.lang("event/tms_home", "start_scan", LibUtils.moment(result?.event?.start_scan).serverFormat('DD MMM YYYY HH:mm'))}</Text>
            </View>
        }


      </View>
    </View>
  )
}
