// withHooks
import { applyStyle } from 'esoftplay';
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 { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/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 { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

import React, { useEffect } from 'react';
import { Pressable, ScrollView, Text, View } from 'react-native';


export interface EventTms_in_failedArgs {

}
export interface EventTms_in_failedProps {

}
export default function m(props: EventTms_in_failedProps): any {
  const { scan_type, ticketItem, text, url_ticket_update, url_ticket_detail, price_type, gate_type, qr_code, event_id, selectGate, typeScanner, event_title, configPriority }: any = LibNavigation.getArgsAll(props)

  const [result, setResult] = useSafeState<any>()
  const [error, setError] = useSafeState<any>()

  let url = url_ticket_detail + LibUtils.objectToUrlParam({
    is_turnstile: 0,
    price_id: ticketItem?.price_id == "staff" ? 0 : ticketItem?.price_id,
    qr: encodeURIComponent(qr_code),
    t: new Date().getTime()
  })


  useEffect(() => {
    EventTms_homeProperty.addCounterEntranceScanFailed(1, ticketItem?.price_id)
    if (ticketItem && url_ticket_detail) {
      getDetailDataTicket()
    }
  }, [])

  function getDetailDataTicket() {
    new LibCurl(url, null, (res, msg) => {
      setResult(res)
    }, (err) => {
      setError(err)
    }, 1)
  }

  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 sendTelegram() {
    let data = {
      '#bbotms': ":",
      reporter: {
        email: UserClass.state().get().email,
        name: UserClass.state().get().name
      },
      "event/gate/type": event_id + "/" + selectGate?.id + "/" + (gate_type == 1 ? "in" : "out"),
      qr: qr_code,
      type_ticket: ticketItem?.price_id,
      qty: ticketItem?.qty,
      qty_used: ticketItem?.qty_used,
      qty_left: ticketItem?.qty_left,
      data: {
        res: result,
        url: url
      },
      error_msg: text,
    }

    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 }}>{text ? text : esp.lang("event/tms_in_failed", "ticket_out")}</Text>
          {
            result &&
            <View style={[applyStyle({ marginTop: 10, padding: 10 }), { width: LibStyle.width }]}>
              {
                result?.length > 0 &&
                <>
                  <Text allowFontScaling={false} style={{ fontSize: 20, color: '#fff', margin: 10, textAlign: 'center', letterSpacing: 1 }}>{esp.lang("event/tms_in_failed", "history")}</Text>
                  <Text allowFontScaling={false} style={{ marginTop: 0, fontSize: 16, color: '#fff', margin: 10, textAlign: 'center', letterSpacing: 1, fontWeight: 'bold' }}>{result?.[0].price_name}</Text>
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', backgroundColor: '#37c2d0', borderTopLeftRadius: 10, borderTopRightRadius: 10 }}>
                    <View style={{ flex: 1.5, justifyContent: 'center', borderRightWidth: 1, borderColor: LibStyle.colorBgGrey, paddingVertical: 5, padding: 5 }}>
                      <Text allowFontScaling={false} style={{ fontWeight: 'bold', textAlign: 'center', fontSize: 14 }}>{esp.lang("event/tms_in_failed", "code")}</Text>
                    </View>
                    <View style={{ flex: 1.2, justifyContent: 'center', paddingVertical: 5 }}>
                      <Text allowFontScaling={false} style={{ fontWeight: 'bold', textAlign: 'center', fontSize: 14 }}>{esp.lang("event/tms_in_failed", "used_time")}</Text>
                    </View>
                    <View style={{ flex: 2, justifyContent: 'center', borderLeftWidth: 1, borderColor: LibStyle.colorBgGrey, paddingVertical: 5 }}>
                      <Text allowFontScaling={false} style={{ fontWeight: 'bold', textAlign: 'center', fontSize: 14 }}>{esp.lang("event/tms_in_failed", "gate")}</Text>
                    </View>
                  </View>
                </>
              }

              {
                result && result?.map?.((item: any, i: number) => {
                  return (
                    <View key={i} style={{ backgroundColor: i % 2 ? '#fff' : LibStyle.colorGrey, flexDirection: 'row', justifyContent: 'space-between', borderBottomWidth: 1, borderBottomColor: LibStyle.colorBgGrey }}>
                      <View style={{ flex: 1.5, justifyContent: 'center', borderRightWidth: 1, borderColor: LibStyle.colorBgGrey, paddingVertical: 5, padding: 5 }}>
                        <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode="tail" style={{ letterSpacing: 1, textAlign: 'center', fontSize: 12 }}>{item?.code}</Text>
                      </View>
                      <View style={{ flex: 1.2, justifyContent: 'center', paddingVertical: 5 }}>
                        {
                          item.scanned != "0000-00-00 00:00:00" &&
                          <Text allowFontScaling={false} style={{ textAlign: 'center', fontSize: 12 }}>{LibUtils.moment(item.scanned).localeFormat("DD MMM H:mm:ss ") + (item.timezone_locale != "" ? item.timezone_locale : "")}</Text>
                        }
                      </View>
                      <View style={{ flex: 2, justifyContent: 'center', borderLeftWidth: 1, borderColor: LibStyle.colorBgGrey, paddingVertical: 5 }}>
                        {
                          item.gate_name != null &&
                          <Text allowFontScaling={false} style={{ letterSpacing: 1, textAlign: 'center', fontSize: 12, }}>{item.tms_email + "\n" + item.gate_name + " - " + item.turnstile_id}</Text>
                        }
                      </View>
                    </View>
                  )
                })
              }
            </View>
          }
          {
            error &&
            <View style={{ width: LibStyle.width - 40, alignSelf: 'center', justifyContent: 'center', alignItems: 'center', padding: 15, borderRadius: 10, marginTop: 100 }}>
              <Text allowFontScaling={false} style={{ flexWrap: 'wrap', fontSize: 14, lineHeight: 20, fontWeight: "bold", marginBottom: 5, color: "#fff", textAlign: "center" }}>{error?.message}</Text>
            </View>
          }
        </ScrollView>
        <View style={{ flexDirection: 'row', width: LibStyle.width - 40, marginVertical: 10, justifyContent: 'space-between' }}>
          <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: 43, borderRadius: 5, backgroundColor: LibStyle.colorRed, borderWidth: 3, borderColor: "#fff", justifyContent: 'center', alignContent: 'center', alignItems: 'center', ...LibStyle.elevation(10) }}>
            <Text allowFontScaling={false} style={{ textAlign: 'center', fontSize: 14, fontWeight: 'bold', color: "#fff" }}>{esp.lang("event/tms_in_failed", "report")}</Text>
          </Pressable>
          <Pressable onPress={getBack} style={{ width: (LibStyle.width - 45) * 0.5, height: 43, borderRadius: 5, backgroundColor: LibStyle.colorGreen, justifyContent: 'center', alignContent: 'center', alignItems: 'center', ...LibStyle.elevation(10) }}>
            <Text allowFontScaling={false} style={{ fontSize: 14, fontWeight: 'bold', color: "#fff" }}>{esp.lang("event/tms_in_failed", "back")}</Text>
          </Pressable>

        </View>
      </View>

    </View>
  )

}