// withHooks
import { EventCounter_eoProperty } from 'esoftplay/cache/event/counter_eo/import';
import { EventCounter_history_item } from 'esoftplay/cache/event/counter_history_item/import';
import { EventCounter_info } from 'esoftplay/cache/event/counter_info/import';
import { EventCounter_menu } from 'esoftplay/cache/event/counter_menu/import';
import { EventCounter_section } from 'esoftplay/cache/event/counter_section/import';
import { EventCounter_user_list_item } from 'esoftplay/cache/event/counter_user_list_item/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibFocus } from 'esoftplay/cache/lib/focus/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/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 esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventConfigProperty } from 'esoftplay/cache/event/config/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventLabel_input } from 'esoftplay/cache/event/label_input/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { EventPopup } from 'esoftplay/cache/event/popup/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import React, { useEffect, useRef } from 'react';
import { Pressable, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventCounter_lmArgs {

}
export interface EventCounter_lmProps {

}
export default function m(props: EventCounter_lmProps): any {
  const { is_manager } = LibNavigation.getArgsAll(props)
  const dialogAdd = useRef<LibSlidingup>(null)
  const dialogUser = useRef<LibSlidingup>(null)
  const [eventConfig] = EventConfigProperty.state().useState()

  const [email, setEmail] = useSafeState<string>('')

  const [result, setResult] = useSafeState<any>()
  const [typeCashier, setTypeCashier] = useSafeState<any>();
  const [refreshing, setRefreshing] = useSafeState<boolean>(false);

  useEffect(() => {
    EventConfigProperty.curlConfig('v2/config_event')
    loadData()
  }, [])

  function loadData() {
    new LibCurl('event_manager_home?event_id=' + is_manager?.id, null, (res, msg) => {
      setResult(res)
      setRefreshing(false)
    }, (error) => {
      LibDialog.warning(esp.lang("event/counter_lm", "load_failed"), error?.message)
      LibNavigation.back()
      setRefreshing(false)
    }, 1)
  }

  function onRefresh() {
    setRefreshing(true)
    loadData()
  }

  function addCashier() {
    if (!typeCashier) {
      LibToastProperty.show(esp.lang("event/counter_eo", "select_cashier_first"))
      return
    }

    let post = {
      event_id: is_manager?.id,
      email: email.trim(),
      is_digital: typeCashier.id
    }

    LibDialog.confirm(esp.lang("event/counter_lm", "cashier_title"), esp.lang("event/counter_lm", "cashier_msg"), esp.lang("event/counter_lm", "cashier_confirm"), () => {
      new LibCurl('event_seller_edit', post, (res, msg) => {
        LibDialog.info(esp.lang("event/counter_lm", "cashier_ok"), msg)
        loadData()
        dialogUser.current?.hide()
      }, (error) => {
        LibDialog.warning(esp.lang("event/counter_lm", "cashier_failed"), error?.message)
        dialogUser.current?.hide()
      }, 1)
    }, esp.lang("event/counter_lm", "cashier_cancel"), () => { })

  }

  function deleteCashier(_email: string) {
    let post = {
      event_id: is_manager?.id,
      email: _email.trim()
    }

    LibDialog.confirm(esp.lang("event/counter_lm", "delete_title"), esp.lang("event/counter_lm", "delete_msg"), esp.lang("event/counter_lm", "delete_confirm"), () => {
      new LibCurl('event_seller_delete', post, (res, msg) => {
        LibDialog.info(esp.lang("event/counter_lm", "delete_ok"), msg)
        loadData()
      }, (error) => {
        LibDialog.warning(esp.lang("event/counter_lm", "delete_failed"), error?.message)
      }, 1)
    }, esp.lang("event/counter_lm", "delete_cancel"), () => { })
  }

  if (!result) {
    return (
      <LibLoading />
    )
  }

  function renderMoneyRequest(item: any, i: number) {
    return (
      <View key={i} style={styleId_ZEwY6z}>
        <EventCounter_history_item item={item} is_ticket={false} onPress={() => LibNavigation.navigate('event/counter_request_detail', { url: item.url, status_user: 2 })} />
      </View>
    )
  }

  function renderTicketRequest(item: any, i: number) {
    return (
      <View key={i} style={styleId_ZEwY6z}>
        <EventCounter_history_item item={item} is_ticket={true} onPress={() => LibNavigation.navigate('event/counter_request_detail', { url: item.url, status_user: 2 })} />
      </View>
    )
  }

  function renderSeller(item: any, i: number) {
    return (
      <EventCounter_user_list_item {...item} key={i} showDelete={is_manager?.add_tms == 1 ? true : false} onDelete={() => { deleteCashier(item.email) }} />
    )
  }

  function renderTypeCashier(item: any, i: number) {
    const styleId_Z23v85x: any = { marginLeft: 5, flexWrap: 'wrap', fontFamily: 'SFProText', color: Number(item.debit) == 0 ? "#717171" : "#000" }
    const styleId_1eMW7i: any = { marginBottom: 5, marginTop: 5, marginRight: 10, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'center' }
    return (
      <Pressable key={i} onPress={() => {
        setTypeCashier(item)
      }} style={styleId_1eMW7i} hitSlop={{ top: 10, left: 10, right: 10, bottom: 10 }}>
        <LibIcon name={item.id == typeCashier?.id ? "radiobox-marked" : "radiobox-blank"} color={item.id == typeCashier?.id ? "#009AE4" : "#000"} />
        <Text allowFontScaling={false} style={styleId_Z23v85x}>{item.title}</Text>
      </Pressable>
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <EventHeader title={esp.lang("event/counter_lm", "header_title")} subtitle={is_manager?.name} bgColor={"#00AA43"} titleColor="#fff" notif />
      <LibFocus onFocus={loadData} />
      {/* status_user 1 EO, 2 LM, 3 Seller */}
      {/* user_type kenapa 3, karena untuk menambahkan Kasir */}
      <EventCounter_menu colorTheme={"#00AA43"} event_id={is_manager?.id} user_type={3} status_user={2} />
      <ScrollView style={{ marginTop: -20, backgroundColor: "#EEF1F8", borderTopLeftRadius: 15, borderTopRightRadius: 15 }} refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }>
        {/* active balance */}
        <EventCounter_info colorTheme={"#00AA43"} amount={result?.money} ticket={result?.ticket} event_id={is_manager?.id} status_user={2} />

        {/* request */}
        {
          result?.money_request?.length > 0 &&
          <EventCounter_section icon="chevron-right-circle" onPress={() => { LibNavigation.navigate('event/counter_request', { event_id: is_manager?.id, status_user: 2 }) }} title={esp.lang("event/counter_lm", "recent_money")} />
        }
        {
          result?.money_request?.length > 0 && result?.money_request?.map(renderMoneyRequest)
        }

        {
          result?.ticket_request?.length > 0 &&
          <EventCounter_section icon="chevron-right-circle" onPress={() => { LibNavigation.navigate('event/counter_request', { event_id: is_manager?.id, status_user: 2 }) }} title={esp.lang("event/counter_lm", "recent_ticket")} />
        }
        {
          result?.ticket_request?.length > 0 && result?.ticket_request?.map(renderTicketRequest)
        }


        {/* Kasir */}
        <EventCounter_section icon="plus-circle" showIcon={is_manager?.add_tms == 1 ? true : false} onPress={() => { dialogAdd.current?.show() }} title={esp.lang("event/counter_lm", "cashier")} />

        {
          result?.seller?.map(renderSeller)
        }

        {
          result?.seller?.length == 0 &&
          <View style={{ margin: 15, marginTop: 0, borderRadius: 15, overflow: 'hidden' }}>
            <EventMessage message={esp.lang("event/counter_lm", "cashier_empty")} />
          </View>
        }

        {
          result?.seller?.length > 9 &&
          <TouchableOpacity onPress={() => { LibNavigation.navigate('event/counter_user_list', { event_id: is_manager?.id, status_user: 2 }) }} style={{ 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={{ alignSelf: 'center', textAlign: 'center', fontFamily: "Arial", fontSize: 11, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b" }}>{esp.lang("event/counter_lm", "show_adll")}</Text>
          </TouchableOpacity>

        }

      </ScrollView>

      <LibSlidingup ref={dialogAdd}>
        <View style={{ backgroundColor: '#fff', borderTopLeftRadius: 20, borderTopRightRadius: 20 }}>
          <View style={{ height: 4, width: 32, borderRadius: 2, backgroundColor: "#C6C6C6", marginTop: 10, marginBottom: 10, alignSelf: 'center' }} />
          <View style={{ margin: 15 }}>
            <EventLabel_input label={esp.lang("event/counter_eo", "label_email")} />

            <EventInput_rectangle
              autoCapitalize="none"
              onChangeText={(t) => {
                LibUtils.debounce(() => {
                  setEmail(t)
                }, 500)
              }}
              style={{ borderColor: '#c4c4c4', height: 35, marginTop: 8, borderRadius: 15, }}
              keyboardType="email-address"
              placeholder={esp.lang("event/counter_lm", "email")}
              onSubmitEditing={() => {
                if (EventCounter_eoProperty.checkEmail(email.trim())) {
                  if (!typeCashier) {
                    LibToastProperty.show(esp.lang("event/counter_eo", "select_cashier_first"))
                  } else {
                    dialogAdd.current?.hide()
                    dialogUser.current?.show()
                  }
                }
              }}
            />

            <EventLabel_input label={esp.lang("event/counter_lm", "label_type")} />
            <View style={{ backgroundColor: '#fff', padding: 10, paddingLeft: 0, borderRadius: 15, marginBottom: 0, flexDirection: 'row', flexWrap: 'wrap' }}>

              {
                eventConfig?.event?.cashier_type?.map(renderTypeCashier)
              }
            </View>

            <EventButton label={esp.lang("event/counter_lm", "btn_next")} style={{ borderRadius: 15, marginTop: 20 }} backgroundColor={email == "" ? LibStyle.colorGrey : "#00AA43"} onPress={() => {
              if (EventCounter_eoProperty.checkEmail(email.trim())) {
                if (!typeCashier) {
                  LibToastProperty.show(esp.lang("event/counter_eo", "select_cashier_first"))
                } else {
                  dialogAdd.current?.hide()
                  dialogUser.current?.show()
                }

              }
            }} />
          </View>
        </View>
      </LibSlidingup>

      <LibSlidingup ref={dialogUser}>
        <View style={{ backgroundColor: '#fff', borderTopLeftRadius: 20, borderTopRightRadius: 20 }}>
          <View style={{ height: 4, width: 32, borderRadius: 2, backgroundColor: "#C6C6C6", marginTop: 10, marginBottom: 10, alignSelf: 'center' }} />
          <EventPopup email={email.trim()} redirect={() => {
            addCashier()
          }} cancel={() => {
            dialogUser.current?.hide()
          }} />
        </View>
      </LibSlidingup>

    </View >
  )
}
const styleId_ZEwY6z: any = { margin: 15, marginTop: 0, borderRadius: 15, backgroundColor: '#fff', overflow: 'hidden' }