// withHooks
import { useEffect } from 'react';

import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventTms_homeProperty } from 'esoftplay/cache/event/tms_home/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStatusbar } from 'esoftplay/cache/lib/statusbar/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { UseCondition } from 'esoftplay/cache/use/condition/import';
import { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Alert, Pressable, ScrollView, Text, View } from 'react-native';


export interface EventTms_in_hall_failedArgs {

}
export interface EventTms_in_hall_failedProps {

}

export default function m(props: EventTms_in_hall_failedProps): any {
  const { scan_type, msgError, postGetData, url_ticket_update, url_ticket_detail, price_type, gate_type, event_id, selectGate, typeScanner, event_title, configPriority }: any = LibNavigation.getArgsAll<any>(props)

  const [, setData, getData] = useSafeState()
  const [qty, setQty, getQty] = useSafeState(1)

  const qtyRef = React.useRef<LibSlidingup>(null)

  useEffect(() => {
    EventTms_homeProperty.addCounterHallInScanFailed(1, "0")
  }, [])

  function getBack() {
    LibNavigation.replace('component/scanner', {
      selectGate: selectGate,
      fromPage: 'event/tms_home',
      event_id: event_id,
      event_title: event_title,
      typeScanner: typeScanner,
      gate_type: gate_type,
      price_type: price_type,
      url_ticket_detail: url_ticket_detail,
      url_ticket_update: url_ticket_update,
      configPriority: configPriority,
      scan_type: scan_type,
    })
  }

  function forceEntrance() {
    let dataEntranceIn = []
    let dataEntranceBackIn = []
    let mustBeEntrance = 0
    let doneEntrance = 0

    const arr: any[] = msgError.result
    dataEntranceIn = arr.filter((x: any) => x?.status_scanned == 2)
    dataEntranceBackIn = arr.filter((x: any) => x?.status_scanned == 5)

    qtyRef.current?.hide()
    LibProgress.show("Processing")

    if (dataEntranceIn.length > 0) {
      mustBeEntrance += 1
      let post = {
        "target-url": `https://api.${esp.config().domain}/gate_checkin`,
        price_id: getData().ticket.price_id,
        qr: encodeURIComponent(postGetData.user_qr),
        trx_id: new Date().getTime() + "" + UserClass.state().get()?.id,
        event_id: event_id,
        gate_id: getData().gate.id,
        is_tms: 1,
        qty: getQty(),
        tms_id: UserClass.state().get()?.id,
        scanned: LibUtils.moment().format('YYYY-MM-DD HH:mm:ss'),
      }
      new LibCurl(url_ticket_update, post,
        (res) => {
          doneEntrance += 1
          if (mustBeEntrance <= doneEntrance) {
            LibProgress.hide()
            Alert.alert("Berhasil masuk ke Gate!", "Silahkan lanjutkan proses masuk ke hall", [
              {
                text: "OK", onPress: () => {
                  LibNavigation.replace("event/tms_in_hall", { scan_type, url_ticket_update, url_ticket_detail, price_type, gate_type, qr_code: postGetData.user_qr, event_id, selectGate, typeScanner, event_title, configPriority })
                }
              }
            ])
          }
        },
        (error) => {
          doneEntrance += 1
          if (mustBeEntrance <= doneEntrance) {
            LibProgress.hide()
          }
        },
      )
    }
    if (dataEntranceBackIn.length > 0) {
      mustBeEntrance += 1
      var post = {
        event_id: event_id,
        ids: JSON.stringify(dataEntranceBackIn.map((x: any) => x.id_out_temporary).slice(0, getQty())),
        gate_id: getData().gate.id,
      }
      new LibCurl('event_tms_out_temporary_in_confirm', post, (result, msg) => {
        doneEntrance += 1
        if (mustBeEntrance <= doneEntrance) {
          LibProgress.hide()
          Alert.alert("Berhasil masuk ke Gate!", "Silahkan lanjutkan proses masuk ke hall", [
            {
              text: "OK", onPress: () => {
                LibNavigation.replace("event/tms_in_hall", { scan_type, url_ticket_update, url_ticket_detail, price_type, gate_type, qr_code: postGetData.user_qr, event_id, selectGate, typeScanner, event_title, configPriority })
              }
            }
          ])
          // LibNavigation.replace("event/tms_in_hall", { scan_type, url_ticket_update, url_ticket_detail, price_type, gate_type, qr_code: postGetData.user_qr, event_id, selectGate, typeScanner, event_title, configPriority })
        }
      }, (error) => {
        doneEntrance += 1
        if (mustBeEntrance <= doneEntrance) {
          LibProgress.hide()
        }
      })
    }
  }

  function sendTelegram() {
    let data = {
      '#bbohallin': ":",
      reporter: {
        email: UserClass.state().get().email,
        name: UserClass.state().get().name
      },
      url: "event_tms_hall",
      post: postGetData,
      error_msg: msgError,
    }

    let post = {
      text: String(JSON.stringify(data || {}, undefined, 2)).replace(/[\[\]\{\}\"]+/g, ''),
      chat_id: '-1001737180019',
      disable_web_page_preview: true
    }

    let _url = "https://api.telegram.org/bot923808407:AAEFBlllQNKCEn8E66fwEzCj5vs9qGwVGT4/sendMessage"
    new LibCurl().custom(_url, post, (res, msg) => { })
  }

  return (
    <View style={{ flex: 1 }}>
      <LibStatusbar style='light' />
      <View style={{ flex: 1 }}>
        <LibPicture source={esp.assets('failed.png')} style={{ flex: 1, height: LibStyle.height, width: LibStyle.width }} /* resizeMode={"stretch"} */ />
      </View>
      <View style={{ flex: 1, position: 'absolute', top: 50, left: 0, right: 0, bottom: 0, alignItems: 'center', alignContent: 'center' }} >
        <ScrollView>
          <View style={{ marginBottom: 20, alignSelf: 'center', borderRadius: LibStyle.width / 3, padding: 10, backgroundColor: '#fff' }}>
            <LibPicture
              source={esp.assets('failed_icon.png')}
              style={{ width: LibStyle.width / 3, height: LibStyle.width / 3 }}
            />
          </View>
          <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 25, color: '#fff', marginHorizontal: 20, textAlign: 'center', letterSpacing: 1 }}>{msgError?.message}</Text>
          <ScrollView>
            <View style={{ minHeight: LibStyle.height * 0.4, marginTop: 30 }}>
              {
                msgError?.result?.length > 0 &&
                <Text allowFontScaling={false} style={{ textAlign: 'center', marginBottom: 10, fontSize: 18, fontWeight: "bold", fontStyle: "normal", letterSpacing: 1.5, color: "#fff" }}>{esp.lang("event/tms_in_hall_failed", "history_used")}</Text>
              }
              {
                msgError?.result?.length > 0 && msgError?.result?.map((item: any, i: number) => {
                  return (
                    <View key={i} style={{ marginBottom: 5, backgroundColor: "#fff", borderRadius: 10, overflow: 'hidden' }}>
                      {
                        item.hasOwnProperty("status_label") && item?.status_label != "" &&
                        <View style={{ backgroundColor: '#37c2d0', padding: 10, }} >
                          <Text allowFontScaling={false} style={{ fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 1.5, color: item?.status == 1 ? item?.status_background : "#fff" }}>{(item?.status_label)?.toUpperCase()}</Text>
                        </View>
                      }
                      <View style={{ padding: 10, flexDirection: 'row', justifyContent: 'space-between', }}>
                        <View style={{ flex: 1 }}>
                          <Text allowFontScaling={false} style={{ marginBottom: 5, fontWeight: 'bold', fontSize: 14 }}>{esp.lang("event/tms_in_hall_failed", "type")}</Text>
                          <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode="tail" style={{ letterSpacing: 1, fontSize: 12 }}>{item?.price_name}</Text>
                        </View>
                        <View style={{ flex: 2 }}>
                          <Text allowFontScaling={false} style={{ marginBottom: 5, fontWeight: 'bold', textAlign: 'center', fontSize: 14 }}>{esp.lang("event/tms_in_hall_failed", "time")}</Text>
                          {
                            item?.hall_scanned != "0000-00-00 00:00:00" &&
                            <Text allowFontScaling={false} style={{ textAlign: 'center', fontSize: 12 }}>{LibUtils.moment(item?.hall_scanned).localeFormat("DD MMM H:mm:ss ")}</Text>
                          }
                        </View>
                        <View style={{ flex: 2 }}>
                          <Text allowFontScaling={false} style={{ marginBottom: 5, fontWeight: 'bold', textAlign: 'center', fontSize: 14 }}>{/*hall*/"TMS - Hall"}</Text>
                          {
                            item?.hall_name != null &&
                            <Text allowFontScaling={false} style={{ letterSpacing: 1, textAlign: 'center', fontSize: 12 }}>{item.hasOwnProperty("tms_email") ? item?.tms_email + "\n" + item?.hall_name : item?.hall_name}</Text>
                          }
                        </View>

                      </View>
                    </View>
                  )
                })
              }
            </View>
          </ScrollView>
        </ScrollView>
        <UseCondition if={msgError?.status_code == 'EV043'}>
          <View style={{ flexDirection: 'row' }} >
            <Pressable onPress={() => {
              LibNavigation.navigateForResult("event/tms_gate_result", { type: "gate", event_id: event_id }, 2123).then((gate) => {
                const ticket = msgError.result[0]
                setData({ gate, ticket })
                const validDataLength = msgError.result?.filter?.((x: any) => (x?.status_scanned == 2 || x?.status_scanned == 5))?.length
                if (validDataLength > 1) {
                  qtyRef.current?.show()
                } else if (validDataLength == 1) {
                  setQty(1)
                  forceEntrance()
                }
              })
            }} style={{ marginHorizontal: 20, flex: 1, height: 40, borderRadius: 5, backgroundColor: LibStyle.colorPrimary, justifyContent: 'center', alignContent: 'center', alignItems: 'center', ...LibStyle.elevation(10) }} >
              <Text allowFontScaling={false} style={{ textAlign: 'center', fontWeight: 'bold', color: "#fff" }}>PAKSA MASUK KE GATE</Text>
            </Pressable>
          </View>
        </UseCondition>
        <View style={{ flexDirection: 'row', width: LibStyle.width - 40, alignItems: 'center', marginVertical: 10, justifyContent: 'center' }}>
          <UseCondition if={msgError?.status_code != 'EV043'}>
            <Pressable onPress={() => {
              LibDialog.warningConfirm(esp.lang("event/tms_in_failed", "warn_title"), esp.lang("event/tms_in_failed", "warn_msg"), esp.lang("event/tms_in_failed", "warn_ok"), () => {
                sendTelegram()
              }, esp.lang("event/tms_in_failed", "warn_no"), () => { })

            }} style={{ width: (LibStyle.width - 45) * 0.5, height: 40, borderRadius: 5, backgroundColor: LibStyle.colorRed, borderWidth: 3, borderColor: "#fff", justifyContent: 'center', alignContent: 'center', alignItems: 'center', ...LibStyle.elevation(10) }}>
              <Text allowFontScaling={false} style={{ textAlign: 'center', fontWeight: 'bold', color: "#fff" }}>{esp.lang("event/tms_in_hall_failed", "report_error")}</Text>
            </Pressable>
          </UseCondition>
          <Pressable onPress={getBack} style={{ width: (LibStyle.width - 45) * 0.5, height: 40, borderRadius: 5, borderWidth: 5, borderColor: LibStyle.colorGreen, justifyContent: 'center', alignContent: 'center', alignItems: 'center', ...LibStyle.elevation(10) }}>
            <Text allowFontScaling={false} style={{ fontWeight: 'bold', color: "#fff" }}>{esp.lang("event/tms_in_hall_failed", "back")}</Text>
          </Pressable>

        </View>
      </View>
      <LibSlidingup ref={qtyRef}>
        <View style={{ backgroundColor: 'white', padding: 20, borderTopLeftRadius: 30, borderTopRightRadius: 30 }} >
          <View style={{ flexDirection: 'row', padding: 20, alignItems: 'center' }} >
            <Pressable onPress={() => { setQty(Math.max(1, qty - 1)) }} >
              <LibIcon.SimpleLineIcons size={40} name='minus' />
            </Pressable>
            <Text allowFontScaling={false} style={{ fontSize: 50, fontWeight: 'bold', textAlign: 'center', flex: 1 }}>{qty}</Text>
            <Pressable onPress={() => { setQty(Math.min(msgError.result?.filter?.((x: any) => (x?.status_scanned == 2 || x?.status_scanned == 5))?.length, qty + 1)) }} >
              <LibIcon.SimpleLineIcons size={40} name='plus' />
            </Pressable>
          </View>
          <EventButton label='Force Entrance' onPress={() => { forceEntrance() }} />
        </View>
      </LibSlidingup >
    </View >
  )
}