// withHooks
import { applyStyle } from 'esoftplay';
import { EventTms_list_item } from 'esoftplay/cache/event/tms_list_item/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';

import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React, { useEffect, useRef } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventEntrancre_listArgs {

}
export interface EventEntrancre_listProps {

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

  const [ticket, setTicket] = useSafeState<any>()
  const [list, setList] = useSafeState<any>()
  const [useAll, setUseAll] = useSafeState<boolean>(false)
  const dialogQty = useRef<LibSlidingup>(null)

  let args = {
    price_type: price_type,
    gate_type: gate_type,
    qr_code: qr_code,
    event_id: event_id,
    event_title: event_title,
    selectGate: selectGate,
    typeScanner: typeScanner,
    url_ticket_detail: url_ticket_detail,
    url_ticket_update: url_ticket_update,
    qty: 1,
    configPriority: configPriority,
    scan_type: scan_type
  }

  useEffect(() => {
    if (tickets?.length == 1) {
      let item = tickets?.[0]
      let a = new Array(Number(item?.qty_left)).fill({
        ...item,
        selected: 0
      })

      let b = a?.map((item: any, i: number) => {
        return { ...item, selected: i == 0 ? 1 : 0 }
      })

      setUseAll(false)
      setList(b)
      setTicket(item)
      LibUtils.debounce(() => {
        if (item.hasOwnProperty("exhibitor_name")) {
          LibNavigation.replace('event/tms_idcard', {
            selectedTicket: item,
            ...args
          })
        } else {
          dialogQty.current!.show()
        }
      }, 100)
    }
  }, [])


  useEffect(() => {
    setUseAll(list?.some((x: any) => x.selected == 0) ? false : true)
  }, [list])

  function useTicket() {
    // LibNavigation.back()
    let arg = {
      ...args,
      qty: list?.filter((it: any) => it.selected).length
    }

    if (tickets?.length == 1) {
      LibNavigation.replace('event/tms_in_success', {
        selectedTicket: ticket,
        ...arg
      })
    } else {
      if (configPriority) { // ini untuk memunculkan priority
        if (configPriority?.filter?.((item: any) => item.id == ticket.price_id).length > 0) {
          LibNavigation.replace('event/tms_in_success', {
            selectedTicket: ticket,
            ...arg
          })
        } else {
          LibNavigation.replace('event/tms_in_warning', {
            selectedTicket: ticket,
            is_from_list: 1, // digunakan untuk membedakan navigasi kalau scan QR Member
            ...arg
          })
        }
      } else {
        LibNavigation.replace('event/tms_in_success', {
          selectedTicket: ticket,
          ...arg
        })
      }
    }

  }

  function renderItem(item: any, i?: number) {
    return (
      <EventTms_list_item
        key={i}
        item={item}
        onPress={() => {
          if (item.text == "") {
            if (item.qty_left == 0) {
              LibNavigation.back()
              LibNavigation.navigate('event/tms_in_failed', {
                text: esp.lang("event/tms_in_list", "ticket_habis"),
                ticketItem: item,
                ...args
              })
            } else {
              let a = new Array(Number(item?.qty_left)).fill({
                ...item,
                selected: 0
              })

              let b = a?.map((item: any, i: number) => {
                return { ...item, selected: i == 0 ? 1 : 0 }
              })

              setUseAll(false)
              setList(b)
              setTicket(item)
              LibUtils.debounce(() => {
                if (item.hasOwnProperty("exhibitor_name")) {
                  LibNavigation.replace('event/tms_idcard', {
                    selectedTicket: item,
                    ...args
                  })
                } else {
                  dialogQty.current!.show()
                }
              }, 100)
            }
          } else {
            LibNavigation.back()
            LibNavigation.navigate('event/tms_in_failed', {
              text: item.text,
              ...args
            })
          }
        }}
      />
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <EventHeader title={esp.lang("event/tms_in_list", "header_title")} subtitle='TMS' />
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop: 15, paddingBottom: 0 }}>
        <ScrollView style={{ flex: 1 }}>
          {
            tickets?.map(renderItem)
          }
        </ScrollView>
      </View>

      {/* dialog qty */}
      <LibSlidingup ref={dialogQty}>
        <View style={{ borderTopRightRadius: 20, borderTopLeftRadius: 20, padding: 20, paddingBottom: 0, backgroundColor: '#fff', maxHeight: LibStyle.height - (LibStyle.height / 3) }}>
          <Text allowFontScaling={false} style={applyStyle({ letterSpacing: 1, fontSize: 30, marginTop: 0, fontWeight: 'bold', textAlign: "center", textAlignVertical: 'center', color: '#000', margin: 15 })} >{esp.lang("event/tms_in_list", "total_ticket", list?.length)}</Text>

          <View style={{ flexDirection: 'row', alignItems: 'center', marginVertical: 20 }} >
            <TouchableOpacity
              onPress={() => {
                const index = findLastIndex(list, (x: any) => x.selected == 1)
                if (index > 0) {
                  setList(LibObject.set(list, 0)(index, 'selected'))
                }
              }}
              style={{ height: 70, width: 70, borderRadius: 10, backgroundColor: '#c1c2c3', alignItems: 'center', justifyContent: 'center' }} >
              <LibIcon name='minus' size={50} />
            </TouchableOpacity>
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }} >
              <Text style={{ fontSize: 50 }} >{list?.filter?.((x: any) => x.selected == 1).length}</Text>
            </View>
            <TouchableOpacity
              onPress={() => {
                const index = list?.findIndex?.((x: any) => x.selected == 0)
                if (index > -1)
                  setList(LibObject.set(list, 1)(index, 'selected'))
              }}
              style={{ height: 70, width: 70, borderRadius: 10, backgroundColor: '#c1c2c3', alignItems: 'center', justifyContent: 'center' }} >
              <LibIcon name='plus' size={50} />
            </TouchableOpacity>
          </View>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', padding: 10, marginBottom: 20, alignContent: 'center', alignItems: 'center' }}>
            <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode={'tail'} style={{ flex: 1, fontWeight: 'bold', fontSize: 14, letterSpacing: 1 }}>{esp.lang("event/tms_in_list", "total_ticket_use", list?.filter((it: any) => it.selected).length)}</Text>
            <TouchableOpacity onPress={() => {
              let a = list?.map((item: any, i: number) => {
                return { ...item, selected: useAll ? 0 : 1 }
              })
              setList(a)
            }} style={applyStyle({ paddingHorizontal: 10, borderWidth: 1, borderColor: 'rgba(0, 0, 0, 0)', height: 35, borderRadius: 16, backgroundColor: useAll ? LibStyle.colorRed : LibStyle.colorGreen, flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center' })} >
              <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: '#fff', marginRight: 15 })} >{useAll ? esp.lang("event/tms_in_list", "cancel_use") : esp.lang("event/tms_in_list", "use_all")}</Text>
              <LibIcon.Ionicons size={18} color="#fff" name={useAll ? "close" : "checkmark-done"} />
            </TouchableOpacity>
          </View>

          <EventButton
            label={esp.lang("event/tms_in_list", "btn_entrance")}
            style={{ borderRadius: 10, marginHorizontal: 5, marginBottom: 10 }}
            backgroundColor={list?.filter((it: any) => it.selected).length == 0 ? LibStyle.colorBgGrey : LibStyle.colorGreen}
            onPress={() => {
              if (list?.filter((it: any) => it.selected).length == 0) {
                LibToastProperty.show(esp.lang("event/tms_in_list", "ticket_not_select"))
              } else {
                useTicket()
              }
            }}
          />
        </View>

      </LibSlidingup >


    </View >
  )
}

function findLastIndex(arr: any[], condition: (value: any, index: number, obj: any[]) => unknown) {
  const reversedArray = arr.slice().reverse();
  const indexInReversedArray = reversedArray.findIndex(condition);

  if (indexInReversedArray === -1) {
    return -1; // No matching element found
  }

  const lastIndex = arr.length - 1 - indexInReversedArray;
  return lastIndex;
}