// 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 esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import useLazyState from 'esoftplay/lazy';
import React, { useEffect, useRef } from 'react';
import { Pressable, 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 [types, setTypes] = useLazyState<any>(undefined)
  const [activeType, setActiveType] = useLazyState<any>()
  const ref = useRef<LibInfinite>(null)

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

  function loadCategories() {
    new LibCurl('event_history_cat', null, (res, msg) => {
      setTypes(res)
      setActiveType(res?.[0])()
    }, (error) => { })
  }

  function buildUrl(type: any): string {
    return type?.url || url
  }

  useEffect(() => {
    loadCategories()
    loadButtonHistoryExist()

    if (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) {
      return
    }
    var post = {
      access_code: argsCode
    }
    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()
      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", "header_title")} />
      <>
        {
          types && types?.length > 0 &&
          <View style={[{ flexDirection: "row", alignItems: "center", marginHorizontal: 15, marginTop: 10 }]}>
            {
              types?.map?.((item: any, index: number) => {
                const tabsLength = types?.length
                const itemWidth = (LibStyle.width - 30) / tabsLength
                return (
                  <Pressable key={index} onPress={() => {
                    setActiveType(item)()
                  }}>
                    <View key={index} style={applyStyle({ height: 43, width: itemWidth, alignItems: 'center', overflow: 'visible', justifyContent: 'center', backgroundColor: '#fff' })}>
                      <Text allowFontScaling={false} style={{
                        width: itemWidth, fontFamily: "Arial", fontSize: item?.type == activeType?.type ? 13 : 12,
                        fontWeight: item?.type == activeType?.type ? "bold" : "normal",
                        fontStyle: "normal", letterSpacing: 0, textAlign: "center",
                        color: item?.type == activeType?.type ? "#51b596" : "#c5c5c5"
                      }}>{item.title}</Text>
                      <View style={{ width: (itemWidth) - 20, height: 3, backgroundColor: item?.type == activeType?.type ? "#51b596" : "#fff", position: 'absolute', bottom: 0 }} />
                    </View>
                  </Pressable>
                )
              })
            }
          </View>
        }
      </>
      <LibInfinite
        ref={ref}
        // isDebug={1}
        key={buildUrl(activeType)}
        errorView={(err: any) => (
          <View style={{ margin: 15 }}>
            <EventMessage message={err} />
          </View>
        )}
        url={buildUrl(activeType)}
        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>
        }
      />

      <TouchableOpacity onPress={() => {
        LibNavigation.replace('bigbang/input_code')
      }} style={{ padding: 5, /* ...LibStyle.elevation(3), */ position: 'absolute', right: 0, bottom: 30, borderTopLeftRadius: 35, borderBottomLeftRadius: 35, backgroundColor: esp.isDebug("ini memang isDebug, tapi jangan di hapus") ? 'rgba(0, 191, 99, 0.1618)' : 'rgba(255, 197, 35, 0.1618)' }}>
        <View style={{ padding: 5, backgroundColor: LibStyle.colorPrimary, ...LibStyle.elevation(3), borderRadius: 30, alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
          <LibPicture source={esp.assets('icons/ic_input.png')} style={{ marginTop: 1, height: 13, width: 26 }} />
          <Text allowFontScaling={false} style={{ fontWeight: 'bold', color: '#000', marginTop: 2, fontSize: 9 }}>{"Code"}</Text>
        </View>
      </TouchableOpacity>

    </View >
  )
}