// withHooks

import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';

import { applyStyle } from 'esoftplay';
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventScan_item } from 'esoftplay/cache/event/scan_item/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import esp from 'esoftplay/esp';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import React, { useEffect } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';
moment().locale('id')


export interface EventTms_in_againArgs {

}
export interface EventTms_in_againProps {

}
export default function m(props: EventTms_in_againProps): any {
  const [result, setResult] = useSafeState<any>(undefined)

  const user_qr = LibNavigation.getArgs(props, 'qr_code')
  const { scan_type, event_id, event_title, selectGate, typeScanner }: any = LibNavigation.getArgsAll(props)

  useEffect(() => {
    loadData()
  }, [])


  function loadData(): void {
    var post = {
      // event_id: "264",
      // user_qr: encodeURIComponent("BBO-H6851"),
      // gate_id: "182"
      event_id: event_id,
      user_qr: encodeURIComponent(user_qr),
      gate_id: selectGate?.id
    }

    new LibCurl('event_tms_out_temporary_in', post, (res) => {
      let a = res?.list?.length > 0 && res.list.map((item: any, i: number) => {
        return ({
          ...item,
          checked: 0
        })
      })
      let b = res?.staff?.length > 0 && res.staff.map((item: any, i: number) => {
        return ({
          ...item,
          checked: 0
        })
      })

      let c = {
        ...res,
        list: res?.list?.length == 0 ? [] : a,
        staff: res?.staff?.length == 0 ? [] : b
      }
      esp.log({ res, c });
      setResult(c)
    }, (error) => {
      LibDialog.warningConfirm(esp.lang("event/tms_in_again", "fault"), error?.message, esp.lang("event/tms_in_again", "back"), () => LibNavigation.back(), "", () => { })
    }, 1)
  }

  function entrance(): void {
    let newData = [...result?.staff, ...result?.list]
    let _ids = newData?.filter((item: any) => item.checked == 1).map((it: any) => it.id)
    if (_ids.length == 0) {
      LibToastProperty.show(esp.lang("event/tms_in_again", "warning_ticket"))
      return
    }

    if (_ids.length == 0) {
      LibToastProperty.show(esp.lang("event/tms_in_again", "warning_ticket"))
      return
    }
    var post = {
      event_id: event_id,
      ids: JSON.stringify(_ids),
      gate_id: selectGate.id
    }

    LibProgress.show(esp.lang("event/tms_in_again", "wait"))
    new LibCurl('event_tms_out_temporary_in_confirm', post, (result, msg) => {
      esp.log({ result, msg, post });
      LibProgress.hide()
      LibDialog.confirm(esp.lang("event/tms_in_again", "info"), result, esp.lang("event/tms_in_again", "ok"), () => {
        LibNavigation.replace('component/scanner', {
          selectGate: selectGate,
          fromPage: 'event/tms_home',
          event_id: event_id,
          event_title: event_title,
          typeScanner: typeScanner,
          scan_type: scan_type
        })
      }, "", () => { })
    }, (error) => {
      esp.log({ error });
      LibDialog.warning(esp.lang("event/tms_in_again", "oops"), error?.message)
      LibProgress.hide()
    })
  }

  function renderTicket(item: any, i: number) {
    return (
      <EventScan_item
        key={i}
        item={item}
        colorFont={"#fff"}
        event_image={result?.event_image}
        style={{ backgroundColor: "#fff" }}
        event_name={result?.event_name}
        event_ondate={result?.event_ondate}
        label={item.status == 0 ? esp.lang("event/tms_in_again", "used") : item.checked == 0 ? esp.lang("event/tms_in_again", "use") : esp.lang("event/tms_in_again", "cancel")}
        onPress={() => {
          if (item?.status == 1) {
            let a = LibObject.set(result, item.checked == 1 ? 0 : 1)('list', i, 'checked')
            setResult(a)
          }
        }}
        colorBackground={item.status == 0 ? LibStyle.colorLightGrey : item.checked == 0 ? LibStyle.colorGreen : LibStyle.colorRed}
      />

    )
  }

  function renderStaff(item: any, i: number) {
    return (
      <View key={i}>

        <View style={{ padding: 10, overflow: 'hidden', flex: 1, flexDirection: 'row', backgroundColor: '#fff', borderBottomColor: LibStyle.colorGrey, borderBottomWidth: 1.5 }}>
          <LibPicture style={applyStyle({ borderRadius: 5, width: LibStyle.width / 4.5, height: LibStyle.width / 4.5, backgroundColor: LibStyle.colorBgGrey })} source={{ uri: item?.image }} />
          <View style={{ marginLeft: 10, flex: 1 }}>
            <Text allowFontScaling={false} ellipsizeMode={'tail'} numberOfLines={2} style={applyStyle({ color: "#000", marginBottom: 4, fontSize: 18, fontWeight: 'bold' })}>{item.name}</Text>
            <Text allowFontScaling={false} ellipsizeMode={'tail'} numberOfLines={2} style={applyStyle({ color: "#000", marginBottom: 4, fontSize: 14 })}>{item.department_name}</Text>
            <Text allowFontScaling={false} ellipsizeMode={'tail'} numberOfLines={2} style={applyStyle({ color: "#000", marginBottom: 4, fontSize: 16 })}>{item.exhibitor_name}</Text>
            {
              item.status == 1 &&
              <EventButton style={applyStyle({ marginTop: 10, alignSelf: 'flex-end', width: LibStyle.width / 3, backgroundColor: (item.status == 0 || item.is_limit == 1) ? LibStyle.colorLightGrey : (item.checked == 0) ? LibStyle.colorGreen : LibStyle.colorRed })} label={
                item.status == 0 ?
                  esp.lang("event/tms_out_temporary", "used") :
                  item.hasOwnProperty("checked") && item.checked == 0 ?
                    esp.lang("event/tms_out_temporary", "use") :
                    esp.lang("event/tms_out_temporary", "cancel")
              } fontColor={"#fff"} onPress={() => {
                let a = LibObject.set(result, item.checked == 1 ? 0 : 1)('staff', i, 'checked')
                setResult(a)
              }} />
            }
          </View>
          <View pointerEvents='none' style={{ position: 'absolute', justifyContent: 'center', transform: [{ rotate: '45deg' }], margin: 1, ...LibStyle.elevation(2), height: 20, width: 170, backgroundColor: LibStyle.colorPrimary, right: -50, top: 25 }} >
            <Text style={{ color: 'white', alignSelf: 'center', fontWeight: 'bold' }} >ID CARD</Text>
          </View>
        </View>
      </View>
    )
  }

  if (!result) return <LibLoading />

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/tms_in_again", "entrance_again")} subtitle={selectGate?.name} cart />
      <ScrollView>
        <View style={{ margin: 15, marginBottom: 0, borderRadius: 7, overflow: 'hidden' }}>
          {
            result?.staff?.length > 0 && result?.staff?.map(renderStaff)
          }
        </View>
        <View style={{ margin: 15, marginBottom: 0, borderRadius: 7, overflow: 'hidden' }}>
          {
            result?.list?.length > 0 && result?.list?.map(renderTicket)
          }
        </View>
      </ScrollView>
      <TouchableOpacity onPress={() => {
        entrance()
      }}>
        <View style={applyStyle({ margin: 10, height: 35, borderRadius: 17, backgroundColor: LibStyle.colorGreen, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 })} >
          <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 12, textAlign: "center", textAlignVertical: 'center', color: 'white', marginRight: 13, marginLeft: 10 })} >{esp.lang("event/tms_in_again", "entrance")}</Text>
        </View>
      </TouchableOpacity>

    </View >
  )
}