// withHooks
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 { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/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 { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import React, { useEffect, useRef } from 'react';
import { KeyboardAvoidingView, Pressable, Text, TouchableOpacity, View } from 'react-native';


export interface EventCounter_sendArgs {

}
export interface EventCounter_sendProps {

}
export default function m(props: EventCounter_sendProps): any {

  const { event_id, status_user } = LibNavigation.getArgsAll(props)
  const [type, setType] = useSafeState<any>(1) // ini type antara cash atau tiket
  const [typeTicket, setTypeTicket] = useSafeState<any>() // ini type tiket
  const [selectedUser, setSelectedUser] = useSafeState<any>()
  const [resultTypeTicket, setResultTypeTicket] = useSafeState<any>()
  const [error, setError] = useSafeState<any>()
  const [showLoading, setShowLoading] = useSafeState<boolean>(false)

  let inputAmount = useRef<LibInput>(null)
  const inputNotes = useRef<EventInput_rectangle>(null)

  let ticketUrl = status_user == 1 ? "event_eo_ticket?event_id=" + event_id : status_user == 2 ? "event_manager_ticket?event_id=" + event_id : "event_seller_ticket?event_id=" + event_id
  let moneyUrl = status_user == 1 ? "event_eo_money?event_id=" + event_id : status_user == 2 ? "event_manager_money?event_id=" + event_id : "event_seller_money?event_id=" + event_id
  let urlLoadData = type == 1 ? moneyUrl : ticketUrl

  let urlTypeTicket = status_user == 1 ? "event_eo_ticket_request_send" : status_user == 2 ? "event_manager_ticket_request_send" : "event_seller_ticket_request_send"
  let urlTypeCash = status_user == 1 ? "event_eo_money_request_send" : status_user == 2 ? "event_manager_money_request_send" : "event_seller_money_request_send"

  let urlSend = type == 1 ? urlTypeCash : urlTypeTicket

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

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

  function loadData() {
    setError(undefined)
    setShowLoading(true)
    new LibCurl(urlLoadData, null, (res, msg) => {
      setResultTypeTicket(res)
      setShowLoading(false)
    }, (error) => {
      setError(error)
    }, 1)
  }

  function checkInput() {
    if (!event_id) {
      LibToastProperty.show(esp.lang("event/counter_send", "empty_event_id"))
      return false
    }
    if (type == 2 && !typeTicket) {
      LibToastProperty.show(esp.lang("event/counter_send", "empty_type_ticket"))
      return false
    }
    if (inputAmount.current?.getText() == "") {
      inputAmount.current?.setError(esp.lang("event/counter_send", "empty_qty"))
      return false
    }
    if (!selectedUser) {
      LibToastProperty.show(esp.lang("event/counter_send", "empty_user"))
      return false
    }
    return true
  }

  function sendRequest() {

    // biar gampang kalo ada apa2
    let postTicket = {
      event_id: event_id,
      price_id: typeTicket?.price_id,
      ondate: typeTicket?.ondate,
      user_id: selectedUser?.user_id,
      user_type: selectedUser?.type,
      qty: inputAmount.current?.getText(),
      notes: inputNotes.current?.getText(),
    }

    let postCash = {
      event_id: event_id,
      user_id: selectedUser?.user_id,
      user_type: selectedUser?.type,
      amount: inputAmount.current?.getText(),
      notes: inputNotes.current?.getText(),
    }

    LibDialog.confirm(esp.lang("event/counter_send", "send_title"), esp.lang("event/counter_send", "send_msg"), esp.lang("event/counter_send", "send_confirm"), () => {
      LibProgress.show(esp.lang("event/counter_send", "send_wait"))
      new LibCurl(urlSend, type == 1 ? postCash : postTicket, (res, msg) => {
        LibProgress.hide()
        LibDialog.info(esp.lang("event/counter_send", "send_ok"), msg)
        LibNavigation.back()
        loadData()
      }, (error) => {
        LibDialog.warning(esp.lang("event/counter_send", "send_no"), error?.message)
        LibProgress.hide()
      }, 1)
    }, esp.lang("event/counter_send", "send_cancel"), () => { })
  }

  let colorTheme = status_user == 1 ? "#009AE4" : status_user == 2 ? "#00AA43" : "#6A0740"

  function renderTypeTicket(item: any, i: number) {
    const styleId_Z23v85x: any = { marginLeft: 5, flexWrap: 'wrap', fontFamily: 'SFProText', color: Number(item.debit) == 0 ? "#717171" : "#000" }
    let itemSelected = item.price_id + item.ondate
    let typeSelected = typeTicket?.price_id + typeTicket?.ondate
    const isAllDate = item.ondate == '0000-00-00'
    return (
      <Pressable key={i} onPress={() => {
        if (Number(item.debit) == 0) {
          LibToastProperty.show(esp.lang("event/counter_send", "ticket_sold"))
        } else {
          inputAmount.current?.setText("")
          setTypeTicket(item)
        }
      }} style={styleId_1eMW7i} hitSlop={{ top: 10, left: 10, right: 10, bottom: 10 }}>
        <LibIcon name={itemSelected == typeSelected ? "radiobox-marked" : "radiobox-blank"} color={Number(item.debit) == 0 ? "#717171" : itemSelected == typeSelected ? colorTheme : "#000"} />
        <Text allowFontScaling={false} style={styleId_Z23v85x}>{item.price_name + " (" + (isAllDate ? esp.lang("event/counter_send", "all_date") : LibUtils.moment(item.ondate).localeFormat("D MMM YYYY")) + ") " + " (" + (Number(item?.debit) - Number(item?.credit)) + ")"}</Text>
      </Pressable>
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/counter_send", "header_title")} subtitle={status_user == 1 ? esp.lang("event/counter_send", "sub_eo") : status_user == 2 ? esp.lang("event/counter_send", "sub_lm") : esp.lang("event/counter_send", "sub_cashier")} />
      <KeyboardAvoidingView style={{ flex: 1 }}>

        <LibScroll style={{ flex: 1 }} onRefresh={loadData}>
          <View style={{ margin: 15, backgroundColor: '#fff', padding: 10, borderRadius: 15, marginBottom: 0, flexDirection: 'row' }}>
            <TouchableOpacity onPress={() => {
              setType(1)
              inputAmount.current?.setText("")
            }} style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
              <TouchableOpacity onPress={() => {
                setType(1)
                inputAmount.current?.setText("")
              }} style={{ marginRight: 10 }} hitSlop={{ top: 10, left: 10, right: 10, bottom: 10 }} >
                <LibIcon name={type == 1 ? "radiobox-marked" : "radiobox-blank"} color={type == 1 ? colorTheme : "#000"} />
              </TouchableOpacity>
              <Text allowFontScaling={false} style={{ flexWrap: 'wrap', fontFamily: 'SFProText', fontWeight: 'bold' }}>{esp.lang("event/counter_send", "text_money")}</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => {
              setType(2)
              inputAmount.current?.setText("")
            }} style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
              <TouchableOpacity onPress={() => {
                setType(2)
                inputAmount.current?.setText("")
              }} style={{ marginRight: 10 }} hitSlop={{ top: 10, left: 10, right: 10, bottom: 10 }} >
                <LibIcon name={type == 2 ? "radiobox-marked" : "radiobox-blank"} color={type == 2 ? colorTheme : "#000"} />
              </TouchableOpacity>
              <Text allowFontScaling={false} style={{ flexWrap: 'wrap', fontFamily: 'SFProText', fontWeight: 'bold' }}>{esp.lang("event/counter_send", "text_ticket")}</Text>
            </TouchableOpacity>
          </View>

          {
            type == 2 &&
            <>
              <View style={{ flexDirection: 'row', justifyContent: 'space-between', margin: 15, marginBottom: 0 }}>
                <Text allowFontScaling={false} style={{ fontWeight: 'bold' }}>{esp.lang("event/counter_send", "ticket_type")}</Text>
              </View>
              {
                error ?
                  <View style={{ margin: 15, borderRadius: 15, marginBottom: 0, backgroundColor: '#fff', overflow: 'hidden' }}>
                    <EventMessage message={error?.message} />
                  </View>
                  :
                  <View style={{ margin: 15, backgroundColor: '#fff', padding: 10, borderRadius: 15, marginBottom: 0, flexDirection: 'row', flexWrap: 'wrap' }}>
                    {
                      showLoading ?
                        <LibLoading />
                        :
                        resultTypeTicket?.map?.(renderTypeTicket)
                    }
                  </View>
              }
            </>
          }

          <View style={{ margin: 15, backgroundColor: '#fff', padding: 10, borderRadius: 15 }}>
            <Text allowFontScaling={false} style={{ alignSelf: 'center', fontWeight: 'bold', fontFamily: 'SFProText' }}>{esp.lang("event/counter_send", "text_amount")}</Text>
            <LibInput
              ref={inputAmount}
              keyboardType="phone-pad"
              maskFrom="end"
              mask="###.###.###.###.###"
              onChangeText={(t) => {
                if (parseInt(inputAmount.current!.getText()) > (Number(typeTicket?.debit) - Number(typeTicket?.credit))) {
                  inputAmount.current?.setError(esp.lang("event/counter_send", "available_ticket", LibUtils.number(Number(typeTicket?.debit) - Number(typeTicket?.credit))))
                  return false
                }
              }}
              label=""
              style={{ marginTop: -15, letterSpacing: 0, fontSize: 30, textAlign: 'center' }}
            />

            <EventInput_rectangle
              ref={inputNotes}
              keyboardType="default"
              placeholder={esp.lang("cashier/invoice", "label_note")}
              maxLength={150}
              onSubmitEditing={() => {
              }}
              inputStyle={{ marginTop: 10, height: 70, textAlignVertical: 'top' }} style={{ margin: 15, marginTop: 0, height: 70, textAlignVertical: 'top', borderRadius: 4 }} multiline />

          </View>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', margin: 15, marginTop: 0, marginBottom: 10 }}>
            <Text allowFontScaling={false} style={{ fontWeight: 'bold' }}>{esp.lang("event/counter_send", "text_choose_user")}</Text>
          </View>

          {
            selectedUser ?
              <EventCounter_user_list_item
                email={selectedUser?.email}
                image={selectedUser?.image}
                name={selectedUser?.name}
                user_id={selectedUser?.user_id}
                showType
                type={selectedUser?.type}
                showChange
                onChange={() => {
                  LibNavigation.navigateForResult('event/counter_user_list', { event_id: event_id, is_navResult: true, status_user: status_user, is_ticket: type }).then((item) => {
                    setSelectedUser(item)
                  })
                }}
                />
              :
              <Pressable onPress={() => {
                LibNavigation.navigateForResult('event/counter_user_list', { event_id: event_id, is_navResult: true, status_user: status_user, is_ticket: type }).then((item) => {
                  setSelectedUser(item)
                })
              }} style={{ margin: 15, marginBottom: 10, marginTop: 0, backgroundColor: '#fff', padding: 10, borderRadius: 15, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
                <Text allowFontScaling={false} style={{ flexWrap: 'wrap', fontFamily: 'SFProText', fontWeight: 'bold' }}>{esp.lang("event/counter_send", "text_select_user")}</Text>
                <LibIcon name={"chevron-right-circle-outline"} color={colorTheme} />
              </Pressable>
          }

        </LibScroll>

        <EventButton label={esp.lang("event/counter_send", "btn_send")} onPress={() => {
          if (checkInput()) {
            sendRequest()
          }
        }} backgroundColor={colorTheme} style={{ margin: 15 }} />

      </KeyboardAvoidingView>

    </View >
  )
}
const styleId_1eMW7i: any = { marginBottom: 5, marginTop: 5, marginRight: 10, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'center' }