// withHooks
import { EventScan_item } from 'esoftplay/cache/event/scan_item/import';
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 { LibObject } from 'esoftplay/cache/lib/object/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 { LibPicture } from 'esoftplay/cache/lib/picture/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React, { useEffect } from 'react';
import { ScrollView, Text, View } from 'react-native';


export interface EventTms_out_temporaryArgs {

}
export interface EventTms_out_temporaryProps {

}
export default function m(props: EventTms_out_temporaryProps): any {
  const user_qr = LibNavigation.getArgs(props, 'qr_code')
  const { scan_type, event_id, selectGate, typeScanner }: any = LibNavigation.getArgsAll(props)
  const [result, setResult] = useSafeState<any>(undefined)
  const [useAll, setUseAll] = useSafeState<boolean>(false)

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

  function loadData() {
    var post = {
      event_id: event_id,
      // event_id: "264",
      user_qr: encodeURIComponent(user_qr),
      gate_id: selectGate.id
      // user_qr: encodeURIComponent("BBO-H6851"),
    }
    new LibCurl('event_tms_out_temporary', 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
      }
      setResult(c)

    }, (error) => {
      LibDialog.warningConfirm(esp.lang("event/tms_out_temporary", "fault"), error?.message, esp.lang("event/tms_out_temporary", "back"), () => LibNavigation.back(), "", () => { })
    }, 1)
  }

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


  const toggleCheckedAll = () => {
    const isAllChecked = result?.list?.every((item: any) => item.checked == 1);
    const newCheckedValue = isAllChecked ? 0 : 1;

    const updatedList = result?.list?.map((item: any) => ({
      ...item,
      checked: newCheckedValue,
    }));

    setResult({ ...result, list: updatedList });
  };

  function quitTemporary(): void {
    let list = [...result?.list, ...result.staff]
    let a = list.filter((item: any) => item.checked == 1).map((it: any) => it.id)

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

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

  if (!result) return <LibLoading />

  let lastStatusScanned = ''
  function renderTicketTemporary(item: any, i: number) {
    const showStatusScanned = lastStatusScanned != item?.status_label
    lastStatusScanned = item?.status_label
    return (
      <View key={i}>
        {
          showStatusScanned &&
          <View style={{ backgroundColor: item?.status == 1 ? '#fff' : "#c5c5c5", padding: 10, borderBottomWidth: 2, borderBottomColor: LibStyle.colorBgGrey }} >
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 1.5, color: item?.status == 1 ? item?.status_background : "#fff" }}>{(item?.status_label).toUpperCase()}</Text>
          </View>
        }
        <EventScan_item
          key={i}
          item={item}
          colorFont={"#fff"}
          style={{ backgroundColor: item?.status == 1 ? "#fff" : "#c5c5c5" }}
          event_image={result?.event_image}
          event_name={result?.event_name}
          event_ondate={result?.event_ondate}
          colorText={item?.status == 1 ? "#000" : LibStyle.colorBgGrey}
          label={
            item.status == 0 ?
              esp.lang("event/tms_out_temporary", "used") :
              item.checked == 0 ?
                esp.lang("event/tms_out_temporary", "use") :
                esp.lang("event/tms_out_temporary", "cancel")
          }
          onPress={() => {
            if (item?.status == 1 && item?.is_limit == 0) {
              let a = LibObject.set(result, item.checked == 1 ? 0 : 1)('list', i, 'checked')
              setResult(a)
            }
          }}
          colorBackground={(item.status == 0 || item.is_limit == 1) ? LibStyle.colorLightGrey : (item.checked == 0) ? LibStyle.colorGreen : LibStyle.colorRed}
        />
      </View>
    )
  }


  let lastStatusStaff = ''
  function renderStaff(item: any, i: number) {
    const showStatusScanned = lastStatusStaff != item?.status_label
    lastStatusStaff = item?.status_label

    return (
      <View key={i}>
        {
          showStatusScanned &&
          <View style={{ backgroundColor: item?.status == 1 ? '#fff' : "#c5c5c5", padding: 10, borderBottomWidth: 2, borderBottomColor: LibStyle.colorBgGrey }} >
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 1.5, color: item?.status == 1 ? item?.status_background : "#fff" }}>{(item?.status_label).toUpperCase()}</Text>
          </View>
        }
        <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>
    )
  }

  const sortedData = result?.list?.length > 0 && result?.list.sort((a: any, b: any) => {
    if (a.is_limit == 0 && b.is_limit != 0) {
      return -1; // a di atas b
    } else if (a.is_limit != 0 && b.is_limit == 0) {
      return 1; // b di atas a
    } else {
      return 0; // urutan relatif tidak berubah
    }
  });

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/tms_out_temporary", "temp_out")} />

      <ScrollView>
        <View style={{ margin: 15, marginBottom: 0, borderRadius: 7, overflow: 'hidden' }}>
          {
            result?.staff?.length > 0 && result?.staff?.map(renderStaff)
          }
        </View>
        <View style={{ margin: 15, borderRadius: 7, overflow: 'hidden' }}>
          {
            sortedData?.length > 0 && sortedData?.map(renderTicketTemporary)
          }
        </View>
      </ScrollView>
      <View style={{ padding: 10, backgroundColor: '#fff' }}>
        {/* <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 10, 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", result?.list?.filter((it: any) => it.checked == 1).length)}</Text>
          <TouchableOpacity onPress={() => {
            toggleCheckedAll()
          }} 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_out_temporary", "btn_exit")}
          backgroundColor={"#fff"}
          borderColor={LibStyle.colorRed}
          fontColor={LibStyle.colorRed}
          onPress={() => {
            quitTemporary()
          }}
        // style={{ marginTop: 20 }}
        />
      </View>
    </View>
  )
}