// withHooks
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventIndexProperty } from 'esoftplay/cache/event/index/import';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventOrder_detailProperty } from 'esoftplay/cache/event/order_detail/import';
import { EventTransaction } from 'esoftplay/cache/event/transaction/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 { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/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 { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import { useEffect, useRef } from 'react';

import React from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventOrder_detail_shareArgs {

}
export interface EventOrder_detail_shareProps {

}
export default function m(props: EventOrder_detail_shareProps): any {
  const { url } = LibNavigation.getArgsAll(props)
  const user = UserClass.state().get()
  let inputEmail = React.useRef<EventInput_rectangle>(null)
  const dialogTickets = useRef<LibSlidingup>(null)
  const [email, setEmail] = useSafeState<string>('')
  const [trxId] = useSafeState(EventTransaction().getTrxId())

  const [result, setResult] = useSafeState<any>()
  const [dataTicket, setDataTicket] = useSafeState()
  const [useAll, setUseAll] = useSafeState<boolean>(false)
  const [dataUser, setDataUser] = useSafeState<any>()

  function loadData(): void {
    new LibCurl(url, null, (res) => {
      setResult(res)
      if (res?.hasOwnProperty('url_share')) {
        loadDataTicket(res?.url_share, res?.price_name)
      }
    }, (error) => {
      LibDialog.warning(esp.lang("event/order_share_to", "load_error"), error?.message);
      LibNavigation.back()
    })
  }

  function loadDataTicket(url: any, price_name: string) {
    new LibCurl(url, null, (res) => {
      let data = res?.length > 0 && res?.map((item: any, i: number) => {
        return ({
          ...item,
          checked: i == 0 ? 1 : 0,
          price_name: price_name
        })
      })
      // esp.log({ data });
      setDataTicket(data)
    }, (error) => {
      LibDialog.warning(esp.lang("event/order_share_to", "load_error"), error?.message);
    })
  }


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

  function loadDataUser(qr?: string) {
    let post: any = {
      email: email || ""
    }
    if (qr) {
      post.qr = qr
    }

    new LibCurl("user_search", post, (res) => {
      setDataUser(res)
      LibUtils.debounce(() => {
        dialogTickets?.current?.show()
      }, 200)
    }, (error) => {
      LibDialog.warning(esp.lang("event/order_share_to", "load_error"), error?.message);
    })

  }

  function shareTicket(p: any) {

    LibDialog.warningConfirm(esp.lang("event/order_share_to", "title_alert_share_ticket"), esp.lang("event/order_share_to", "msg_alert_share_ticket"), esp.lang("event/order_share_to", "btn_yes_alert_share_ticket"), () => {
      let seatName = dataTicket?.filter((item: any) => item.checked == 1).map((it: any) => it.seat_name)
      let hasSeat = seatName?.some((v: any) => v.trim())
      let _bookingMemberId = dataTicket?.filter((item: any) => item.checked == 1).map((it: any) => it.id)

      let post: any = {
        receiver_email: dataUser?.email,
        booking_id: result?.booking_id,
        qty_shared: dataTicket?.filter((item: any) => item.checked == 1).length,
        booking_member_id: _bookingMemberId.join('|'),
        trx_id: trxId,
        pin: p
      }

      if (hasSeat) {
        post.seat_name = seatName?.join('|')
      }

      LibProgress.show(esp.lang("event/order_share_to", "msg_wait"))
      new LibCurl('event_booking_shared?id=' + result?.event_id, post, (res, msg) => {
        // LibNotify(result)
        EventOrder_detailProperty.subscribe().trigger()
        EventIndexProperty.reload.trigger() //reload data order
        LibProgress.hide()
        LibDialog.info(esp.lang("event/order_share_to", "title_curl_success"), msg)
        LibNavigation.back()
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/order_share_to", "share_error"), error?.message);
        LibNavigation.back()
      }, 1)
    }, esp.lang("event/order_share_to", "btn_cancel_alert_share_ticket"), () => {

    })
  }

  let checkNotUsed = dataTicket?.length > 0 && dataTicket?.filter((x: any) => x?.checked == 0)
  let valid = dataTicket?.some((item: any) => item.checked == 1);

  return (
    <LibKeyboard_avoid style={{ flex: 1, backgroundColor: '#fff' }}>
      <EventHeader title={esp.lang("event/order_share_to", "title_share_ticket_to", esp.appjson().expo.name)} />
      <ScrollView showsVerticalScrollIndicator={false} >
        <TouchableOpacity onPress={() => {
          LibNavigation.navigateForResult('component/scanner').then((value: any) => {
            loadDataUser(value)
            // esp.log(value);
          })
        }}>
          <View style={{ width: LibStyle.width, height: LibStyle.height * 0.5, backgroundColor: '#b8b7bf', justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
            <LibPicture source={esp.assets('icons/ic_barcode_white.png')} style={{ height: 250, width: 250 }} />
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", marginTop: 10, color: '#fff' }}>{esp.lang("event/order_share_to", "click_here")}</Text>
            <Text allowFontScaling={false} style={{ color: '#fff', fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", marginTop: 6 }}>{esp.lang("event/order_share_to", "scan_qrcode")}</Text>
            <Text allowFontScaling={false} style={{ color: '#fff', fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, textAlign: "center", marginTop: 5 }}>{esp.lang("event/order_share_to", "in_member_bbo_page", esp.appjson().expo.name)}</Text>
          </View>
        </TouchableOpacity>
        <Text allowFontScaling={false} style={{ opacity: 0.6, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, textAlign: "center", marginTop: 17 }}>{esp.lang("event/order_share_to", "or")}</Text>
        <EventInput_rectangle
          ref={inputEmail}
          keyboardType="email-address"
          placeholder={esp.lang("event/order_share_to", "placeholder_input_email")}
          autoCapitalize="none"
          onChangeText={(t) => {
            setEmail(t)
          }}
          style={{ marginLeft: 25, marginRight: 25, marginTop: 18, borderRadius: 5 }} />
        <TouchableOpacity onPress={() => {
          if (inputEmail.current?.getText() == '') {
            LibToastProperty.show(esp.lang("event/order_share_to", "msg_error_input_email"))
            inputEmail.current?.blur()
            return
          } else if (email === user.email) {
            LibDialog.warningConfirm(esp.lang("event/order_share_to", "title_alert_fault"), esp.lang("event/order_share_to", "msg_alert_cant_share_ticket_to_myself"), esp.lang("event/order_share_to", "btn_yes_alert_cant_share_ticket_to_myself"), () => {
              setEmail("")
              inputEmail.current?.setText("")
              inputEmail.current?.focus()
            }, "", () => {

            })
          } else {
            loadDataUser()
          }

          // dialogTickets.current?.show()
        }} >
          <View style={{ marginBottom: 10, marginTop: 18, marginLeft: 25, marginRight: 25, height: 35, borderRadius: 5, backgroundColor: "#34a2ec", borderStyle: "solid", borderWidth: 0.5, borderColor: "#2980b9", alignItems: 'center', justifyContent: 'center' }} >
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: "#fff" }} >{esp.lang("event/order_share_to", "next")}</Text>
          </View>
        </TouchableOpacity>
      </ScrollView>
      <LibSlidingup ref={dialogTickets} >
        <View style={{ backgroundColor: 'white', borderTopLeftRadius: 20, borderTopRightRadius: 20, padding: 15, paddingTop: 5, maxHeight: LibStyle.height - (LibStyle.height / 3) }} >
          <View style={{ alignSelf: 'center', height: 3, width: 35, backgroundColor: "#c5c5c5", borderRadius: 10 }} />
          <Text allowFontScaling={false} style={{ color: '#4a4a4a', fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, marginTop: 15 }}>{esp.lang("event/order_detail_share", "ticket_will_share_to")}</Text>

          <View style={{ marginVertical: 15, flexDirection: 'row' }}>
            <LibPicture source={{ uri: dataUser?.image }} style={{ height: 40, width: 40, borderRadius: 20 }} />
            <View style={{ marginLeft: 10 }}>
              <Text style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", color: "#4a4a4a" }} >{dataUser?.name}</Text>
              <Text style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", color: "#b7b7b7" }} >{dataUser?.email}</Text>
            </View>
          </View>
          <ScrollView>
            <Text allowFontScaling={false} style={{ marginBottom: 10, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 1.5, color: "#000" }}>{esp.lang("event/order_detail_share", "chose_ticket")}</Text>

            {
              dataTicket?.length > 0 && dataTicket?.map((item: any, i: number) => {
                const [front, end] = item?.seat_name?.split("#") || ["", ""];
                return (
                  <TouchableOpacity key={i} onPress={() => {
                    let a = LibObject.set(dataTicket, item.checked == 1 ? 0 : 1)(i, 'checked')
                    setDataTicket(a)
                    setUseAll(false)

                  }} style={{ padding: 10, marginBottom: 10, borderRadius: 4, borderColor: item?.checked == 1 ? LibStyle.colorGreen : '#f1f1f1', borderWidth: 1, flexDirection: 'row' }}>
                    <View style={{ flex: 5 }}>
                      <Text allowFontScaling={false} style={{ fontSize: 14, fontStyle: "normal", color: "#000", fontWeight: "bold", }}>{item?.price_name}</Text>
                      {/* seat */}
                      {
                        item?.seat_name != "" &&
                        <View style={{ marginVertical: 10 }}>
                          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, marginBottom: 5, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "seat_number")}</Text>

                          <View style={{ marginLeft: 7, flexDirection: 'row' }}>
                            <View style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 5, paddingHorizontal: 5, backgroundColor: '#f1f1f1', borderRadius: 5, marginRight: 7 }}>
                              <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 16, color: "#000" }}> {front}</Text>
                              <Text allowFontScaling={false} style={{ marginLeft: 3, fontWeight: 'bold', fontSize: 16, color: '#000', }}>{end}</Text>
                            </View>
                          </View>
                        </View>
                      }
                      {/* add ons */}
                      {
                        item?.addons?.length > 0 &&
                        <View style={{ marginBottom: 5 }}>
                          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "addons")}</Text>
                        </View>
                      }
                      {
                        item?.addons?.length > 0 && item?.addons?.map((x: any, ii: number) => {
                          return (
                            <View key={ii} style={{ marginLeft: 7, flexDirection: 'row' }}>
                              <View style={{}}>
                                <Text allowFontScaling={false} style={{ color: '#484848', fontSize: 12, fontWeight: 'bold', fontFamily: "Arial" }}>- {
                                  x?.list?.map((y: any) => y).join(', ')
                                }</Text>
                                {
                                  x?.ondate != "0000-00-00" &&
                                  <Text allowFontScaling={false} style={{ marginLeft: 7, marginBottom: 3, marginTop: 3, fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: '#484848' }}>{
                                    LibUtils.moment(x?.ondate).localeFormat('DD MMM YYYY')}</Text>
                                }
                              </View>
                            </View>
                          )
                        })
                      }


                    </View>
                    <View style={{ flex: 1, alignContent: 'flex-end', alignItems: 'flex-end' }}>
                      <LibIcon name={item?.checked == 1 ? 'check-circle' : 'radiobox-blank'} color={LibStyle.colorGreen} />
                    </View>
                  </TouchableOpacity>
                )
              })
            }

          </ScrollView>

          <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'space-between' }}>
            <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode={'tail'} style={{ fontWeight: 'bold', fontSize: 14, letterSpacing: 1 }}>{dataTicket?.filter((item: any) => item.checked == 1).length + " Tiket digunakan"}</Text>
            <TouchableOpacity onPress={() => {
              let a = dataTicket?.map((item: any, i: number) => {
                return { ...item, checked: useAll ? 0 : 1 }
              })
              setDataTicket(a)
              setUseAll(useAll ? false : true)
            }} style={{ paddingHorizontal: 15, paddingRight: 10, marginTop: 10, borderWidth: 1, borderColor: 'rgba(0, 0, 0, 0)', height: 25, borderRadius: 5, backgroundColor: (useAll || checkNotUsed?.length == 0) ? LibStyle.colorRed : LibStyle.colorGreen, flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center' }} >
              <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: '#fff', marginRight: 15 }} >{(useAll || checkNotUsed?.length == 0) ? esp.lang("event/order_detail_share", "cancel") : esp.lang("event/order_detail_share", "select_all")}</Text>
              <LibIcon.Ionicons size={18} color="#fff" name={(useAll || checkNotUsed?.length == 0) ? "close" : "checkmark-done"} />
            </TouchableOpacity>
          </View>

          <EventButton
            label={esp.lang("event/order_detail_share", "share_ticket")}
            onPress={() => {
              if (valid) {
                LibNavigation.navigateForResult("bigbang/payment_pin", undefined, 1132).then((p) => {
                  if (p) {
                    shareTicket(p)
                  }
                })
              }
            }}
            backgroundColor={valid ? LibStyle.colorPrimary : LibStyle.colorBgGrey}
            style={{ borderRadius: 5, marginTop: 10 }}
          />
        </View>
      </LibSlidingup>

    </LibKeyboard_avoid>
  )
}