// withHooks
import { applyStyle } from 'esoftplay';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { EventVisitor_history_item } from 'esoftplay/cache/event/visitor_history_item/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibInfinite } from 'esoftplay/cache/lib/infinite/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 esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventLabel_input } from 'esoftplay/cache/event/label_input/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import React, { useEffect, useRef } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';

export interface EventVisitor_indexArgs {

}
export interface EventVisitor_indexProps {

}
export default function m(props: EventVisitor_indexProps): any {
  const { code } = LibNavigation.getArgsAll(props)
  const url = 'event_history'
  const [argsCode, setArgsCode] = useSafeState(code)
  const [isExist, setIsExist] = useSafeState(0)
  const ref = useRef<LibInfinite>(null)
  let inputAccessCode = React.useRef<EventInput_rectangle>(null)

  function loadButtonHistoryExist() {
    new LibCurl('event_history_history_exists', null, (res, msg) => {
      setIsExist(1)
    }, (error) => {
      setIsExist(0)
    })
  }

  useEffect(() => {
    loadButtonHistoryExist()
    if (argsCode) {
      inputAccessCode?.current?.setText(argsCode)
      LibUtils.debounce(() => {
        doSubmit()
      }, 200)

    }
  }, [])

  function doAction(url: string, type: string, data: any): void {
    new LibCurl(url, null, (res, msg) => {

      ref.current?.loadData()
      if (type == '2') {
        LibNavigation.navigate('event/visitor_input', { data: res, url: url })
      } else if (type == '3') {
        if (res.image == '') {
          LibNavigation.navigate('event/visitor_edit', { data: res })
        } else {
          LibNavigation.navigate('staff/id_card', { data: res, withUser: 'y' })
        }
      } else {
        LibNavigation.navigate('event/order_detail', { url: url })
      }
    }, (error) => {
      LibDialog.warning(esp.lang("event/visitor_index", "act_err"), error?.message)
    })
  }

  function doSubmit(): void {
    if (!argsCode) {
      if (inputAccessCode?.current?.getText() == '') {
        LibToastProperty.show(esp.lang("event/visitor_index", "alert_error_not_empty_code"))
        return
      }
    }
    var post = {
      access_code: argsCode ? argsCode : inputAccessCode?.current?.getText().toUpperCase()
    }
    LibProgress.show(esp.lang("event/visitor_index", "waiting_msg"))
    new LibCurl('event_exhibitor_code', post, (res, msg) => {
      setArgsCode(undefined) // reset code supaya pas textbox kosong tidak bisa submit
      ref.current?.loadData()
      inputAccessCode.current?.setText("")
      if (res.hasOwnProperty('qty')) {
        new LibCurl(res?.url, null, (result, msg) => {
          LibNavigation.navigate('event/visitor_input', { data: result, msg: msg, url: res.url })
          LibProgress.hide()
        }, (error) => {
          LibProgress.hide()
        })
      } else {
        LibProgress.hide()
        LibNavigation.navigate('event/visitor_edit', { from: "visitor", data: res })
        LibDialog.info(esp.lang("event/visitor_index", "alert_success_submit"), msg);
      }
    }, (error) => {
      LibProgress.hide();
      LibDialog.warning(esp.lang("event/visitor_index", "err"), error?.message);
    })
  }

  function renderItem(item: any) {
    return (
      <EventVisitor_history_item item={item} doAction={() => doAction(item.url, item.type, item)} />
    )
  }


  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/visitor_index", "title_input_code")} subtitle={esp.lang("event/visitor_index", "subtitle_input_code")} />
      <LibInfinite
        ref={ref}
        // isDebug={1}
        ListHeaderComponent={
          <>
            <View style={{ flexDirection: 'row', borderRadius: 10, backgroundColor: '#FEFBEB', borderColor: "#FFCC29", borderWidth: 1, borderStyle: 'dashed', alignContent: 'center', alignItems: 'center', margin: 15, marginBottom: 0, padding: 10 }}>
              <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0 }} >{esp.lang("event/visitor_index", "please_input_your_exhibitor_code")}</Text>
            </View>


            <View style={[{ margin: 15, backgroundColor: 'white', padding: 15, paddingTop: 8 }, LibStyle.elevation(2)]}>
              <EventLabel_input label={esp.lang("event/visitor_index", "label_input_code")} mandatory />
              <EventInput_rectangle
                ref={inputAccessCode}
                placeholder={esp.lang("event/visitor_index", "input_code")}
                style={{ borderRadius: 3, height: 35 }}
                autoCapitalize='characters'
                returnKeyType='go'
                onSubmitEditing={() => {
                  inputAccessCode.current!.blur()
                  doSubmit()
                }}
                blurOnSubmit
              />

              <TouchableOpacity onPress={() => {
                inputAccessCode.current!.blur()
                doSubmit()
              }}>
                <View style={{ 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>

            <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 14, margin: 15, marginBottom: 0 }} >{esp.lang("event/visitor_index", "history")}</Text>
          </>
        }
        errorView={(err: any) => (
          <View style={{ margin: 15 }}>
            <EventMessage message={err} />
          </View>
        )}
        url={url}
        renderItem={renderItem}
        ListEndedComponent={
          esp.isDebug('') && isExist == 1 &&
          <TouchableOpacity onPress={() => { LibNavigation.navigate('event/visitor_history') }}>
            <View style={applyStyle({ marginBottom: 20, marginTop: 15, justifyContent: 'center', alignSelf: 'center', width: 104, height: 23, borderRadius: 11.5, backgroundColor: "#fff", borderStyle: "solid", borderWidth: 1, borderColor: "#e1e1e1" })}>
              <Text allowFontScaling={false} style={applyStyle({ alignSelf: 'center', textAlign: 'center', fontFamily: "Arial", fontSize: 11, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b" })}>{esp.lang("event/visitor_index", "show")}</Text>
            </View>
          </TouchableOpacity>
        }
      />

    </View >
  )
}