// withHooks
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventOrder_itemProperty } from 'esoftplay/cache/event/order_item/import';
import { EventReview_addProperty } from 'esoftplay/cache/event/review_add/import';
import { LibCarrousel_snap } from 'esoftplay/cache/lib/carrousel_snap/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/import';
import { LibSkeleton } from 'esoftplay/cache/lib/skeleton/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';

import { applyStyle } from 'esoftplay';
import { EventAlert } from 'esoftplay/cache/event/alert/import';
import { EventButton_order_detail } from 'esoftplay/cache/event/button_order_detail/import';
import { EventConfigProperty } from 'esoftplay/cache/event/config/import';
import { EventHtmltext } from 'esoftplay/cache/event/htmltext/import';
import { EventIndexProperty } from 'esoftplay/cache/event/index/import';
import { EventOrder_detail_addons } from 'esoftplay/cache/event/order_detail_addons/import';
import { EventOrder_detail_addons_booked } from 'esoftplay/cache/event/order_detail_addons_booked/import';
import { EventOrder_detail_coupon } from 'esoftplay/cache/event/order_detail_coupon/import';
import { EventOrder_detail_instruction } from 'esoftplay/cache/event/order_detail_instruction/import';
import { EventOrder_detail_reschedule } from 'esoftplay/cache/event/order_detail_reschedule/import';
import { EventOrder_detail_review } from 'esoftplay/cache/event/order_detail_review/import';
import { EventOrder_detail_tnc } from 'esoftplay/cache/event/order_detail_tnc/import';
import { EventQr_bg } from 'esoftplay/cache/event/qr_bg/import';
import { EventSecure_page } from 'esoftplay/cache/event/secure_page/import';
import { LibCollaps } from 'esoftplay/cache/lib/collaps/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { UseCondition } from 'esoftplay/cache/use/condition/import';
import esp from 'esoftplay/esp';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import useGlobalSubscriber, { useGlobalSubscriberReturn } from 'esoftplay/subscribe';
import React, { useEffect, useRef } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import QRCode from 'react-native-qrcode-svg';


export interface EventOrder_detailProps {
  navigation: any
}

const subs = useGlobalSubscriber()
export function subscribe(): useGlobalSubscriberReturn {
  return subs
}

export default function m(props: EventOrder_detailProps): any {
  const LibCurl = esp.mod("lib/curl")

  EventSecure_page()

  let showQR = useRef<LibSlidingup>(null)
  let dialogAddonList = useRef<LibSlidingup>(null)
  let dialogQtyAddons = useRef<LibSlidingup>(null)
  const url = LibNavigation.getArgs(props, 'url')
  const [result, setResult] = useSafeState<any>(EventIndexProperty?.stateTicketCache()?.get()?.filter?.((x: any) => x.url?.replace?.('?id=', '/') == url?.replace?.('?id=', '/'))?.[0]?.detail)
  const useIndividualQr = result?.config?.use_individual_qr_ticket

  const [, setGroupAddon, getGroupAddon] = useSafeState()
  const [, setSelectedAddon, getSelectedAddon] = useSafeState()
  const [addonsCacheBooked, setAddOnsCacheBooked] = EventIndexProperty?.stateBookedAddonsCache()?.useState()
  const [addonsBooked, setAddOnsBooked] = useSafeState(addonsCacheBooked[result?.id])
  const [errorAddonsBooked, setErrorddOnsBooked] = useSafeState()

  const dataOfflineReview = EventReview_addProperty.state().get()
  let availableOfflineReview = dataOfflineReview?.filter((z: any) => z?.booking_id == result?.id)
  const [dataReview, setDataReview] = useSafeState<any>(availableOfflineReview?.length == 1 ? availableOfflineReview[0] : result?.detail_review)

  const [dataTicket, setDataTicket] = useSafeState()

  moment().locale?.('id')

  const imgWidth = LibStyle.width - 30
  const imgHeight = imgWidth / 1920 * 1080
  // const imgHeight = imgWidth / 2

  function loadData(): void {
    new LibCurl(url + ((url.includes("?") ? "&" : "?") + 't=' + new Date().getTime()), null, (res: any) => {
      setResult(res)

      if (res?.review_status != 0) {
        loadDetailReview(res?.url_review)
      }

      // ngirim review offline ke server
      if (availableOfflineReview?.length > 0) {
        sendReview(availableOfflineReview[0])
      }

      if (res?.url_addons_booked == "") return;
      loadDataAddonsBooked(res?.url_addons_booked, res.id);

    }, (error: any) => {
      const transformedUrl = url?.includes("?id=") ? url?.replace(/\?id=/, '/') : url
      const urlArr = transformedUrl?.split("/")
      const id = urlArr[urlArr.length - 1]
      LibDialog.warningConfirm(esp.lang("event/order_detail", "load_err"), error?.message, esp.lang("event/order_detail", "closed"), () => {
      }, "", () => {
        LibNavigation.navigate('event/order_detail_visitor', { url: "event_order_detail_ticket/" + id, url_addition: "event_order_detail_addition/" + id })
      })
      LibNavigation.back()
    })
  }

  function syncQty() {
    let post = {
      booking_id: result?.id
    }
    LibProgress.show(esp.lang("event/order_detail", "please_wait"))
    new LibCurl(result?.url_sync, post, (ress: any) => {
      loadData()
      LibProgress.hide()
    }, (error: any) => {
      LibProgress.hide()
      // setEmptyCoupons(error)
    })
  }

  function loadDetailReview(url: any) {
    new LibCurl(url, null, (ress: any) => {
      setDataReview(ress)
    }, (error: any) => {
      // setEmptyCoupons(error)
    })
  }

  function loadDataTicket(id: any, price_id: string, ondate: string) {
    let param = {
      booking_id: id, price_id: price_id, ondate: ondate
    }

    new LibCurl("addons_item" + LibUtils.objectToUrlParam(param), null, (ress: any) => {
      let data = ress?.length > 0 && ress?.map((item: any, i: number) => {
        return ({
          ...item,
          checked: 0,
        })
      })
      setDataTicket(data)
      LibUtils.debounce(() => { dialogQtyAddons?.current?.show() }, 100)
    }, (error: any) => {
      // setEmptyCoupons(error)
    }, 1)
  }


  function loadDataAddonsBooked(url: string, bookingId: any) {
    new LibCurl(url, null, (ress) => {
      setAddOnsCacheBooked(LibObject.set(EventIndexProperty?.stateBookedAddonsCache().get(), ress)(bookingId))
      setAddOnsBooked(ress)
      setErrorddOnsBooked(undefined)
    }, (error) => {
      setAddOnsCacheBooked(LibObject.removeKeys(EventIndexProperty?.stateBookedAddonsCache().get(), bookingId)())
      setErrorddOnsBooked(error)
    });
  }

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

  function sendReview(data: any) {
    new LibCurl(data?.url, data?.post, (res: any, msg: any) => {
      let a = EventReview_addProperty.state().get()?.filter((it: any) => {
        return it.booking_id != availableOfflineReview[0].booking_id
      })
      EventReview_addProperty.state().set(a)
    }, (err: any) => {
      // LibProgress.hide()
      // LibToastProperty.show(err?.message)
    }, 1)
  }

  subs.useSubscribe(() => {
    loadData()
  })

  function loadDataAddons(id: any, url: string) {
    LibProgress.show(esp.lang("event/order_detail", "wait"))
    new LibCurl(url, null, (res: any, msg: any) => {
      let _bookingMemberId = dataTicket?.filter((item: any) => item.checked == 1).map((it: any) => it.id)
      LibProgress.hide()
      let dataBookingEvent = {
        event_id: res?.event_id,
        event_title: res?.event_name,
        selected_ticket: {
          price_id: res?.price_id,
          currency: res?.currency,
          tax: res?.tax,
          fee: res?.fee,
          fee_percent: res?.fee_percent,
          term: res?.term,
          has_addition: res?.has_addition,
          list: {
            ondate: res?.ondate,
            price: res?.price,
            price_id: res?.price_id,
            currency: res?.currency,
          }
        },
        qty: dataTicket?.filter((item: any) => item.checked == 1).length,
        booking_member_ids: JSON.stringify(_bookingMemberId)
      }
      let fee_platform = {
        fee_platform_amount: res?.fee_platform?.fee_platform_amount,
        fee_platform_type: res?.fee_platform?.fee_platform_type
      }
      let show_fee_percentage = res?.show_fee_percentage
      let tax = res?.tax
      let order_type = EventConfigProperty.state().get()?.order_type?.ticket
      let addons_id = id
      let booking_id_ref = result?.id

      function goToPayment() {
        let args: any = {
          order_type: order_type,
          tax: tax,
          fee_platform: fee_platform,
          dataBookingEvent: dataBookingEvent,
          show_fee_percentage,
          addons_id,
          booking_id_ref
        }
        curlPriceConfig(res?.url_price_config, res?.price_id, (conf) => {
          args['tax'] = conf?.tax
          args['fee_platform'] = conf.hasOwnProperty('fee_platform_amount') ? {
            fee_platform_amount: conf?.fee_platform_amount || 0,
            fee_platform_type: conf?.fee_platform_type || "NONE"
          } : fee_platform
          args['fee_custom'] = {
            fee_custom_label: conf?.fee_custom_label || "Custom Fee",
            fee_custom_amount: conf?.fee_custom_amount || 0,
            fee_custom_type: conf?.fee_custom_type || "NONE"
          }

          esp.log(conf, res?.price_id, args);
          LibNavigation.navigate('payment/ticket', args)
        })
      }

      if (res?.hasOwnProperty('alert') && res?.alert != "") {
        LibDialog.warningConfirm("Informasi", res?.alert, "Lanjutkan", () => {
          goToPayment()
        }, esp.lang("event/order_detail", "back"), () => {

        })
      } else {
        goToPayment()
      }


    }, (err: any) => {
      LibProgress.hide()
      LibDialog.warning("Oops", err?.message)
    }, 1)
  }

  function curlPriceConfig(url_price_config: string, price_id: string, onDone: (data: any) => void) {
    LibProgress.show("Mohon tunggu..")
    if (url_price_config) {
      new LibCurl(url_price_config, null, (res, msg) => {
        onDone(res?.[price_id])
        LibProgress.hide()
      }, (err) => {
        LibProgress.hide()
        LibToastProperty.show(err?.message)
      })
    }
  }

  if (result == undefined) {
    return (
      <View style={{ flex: 1, backgroundColor: '#f6f6f6' }}>
        <EventHeader title={esp.lang("event/order_detail", "order_detail")} />
        <LibSkeleton>
          <View style={applyStyle({ margin: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#fff', height: '10%', width: '92.5%' })} />
          <View style={{ margin: 15, marginBottom: 0, borderTopLeftRadius: 7, borderTopRightRadius: 7, width: '92.5%', height: '50%', backgroundColor: '#fff' }} />
          <View style={{ margin: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#fff', height: '20%', width: '92.5%' }} />
          <View style={{ margin: 15, borderRadius: 7, backgroundColor: '#fff', height: '30%', width: '92.5%' }} />
        </LibSkeleton>
      </View>
    )
  }

  const curr = result?.hasOwnProperty('currency') ? result?.currency : ''

  const dateRange = LibUtils.getDateRange(result?.start_date, result?.end_date, " - ")
  let isInvitationDate = result?.ondate == "0000-00-00" && result?.kind_detail?.use_code == 1
  let isOnlineWithoutDate = result?.ondate == "0000-00-00" && result?.kind_detail?.everyday_pass == 0


  if ((result?.status == 1 || (result?.qty == 0 && result?.qty_shared > 0)) && result?.is_reschedule == 1) {
    return <EventOrder_detail_reschedule dataTicket={result} onPressQr={() => { showQR?.current?.show() }} />
  }

  let valid = dataTicket?.some((item: any) => item.status == 1 && item.checked == 1);

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/order_detail", "order_detail")} />
      <LibScroll onRefresh={loadData}>
        {
          (result?.status != 0)
          &&
          // detail ticket
          <View style={{ margin: 15, marginBottom: 0, borderTopLeftRadius: 7, borderTopRightRadius: 7, backgroundColor: '#fff', paddingBottom: 10 }}>
            <TouchableOpacity onPress={() => {
              LibNavigation.navigate('lib/gallery', { image: result?.image })
            }}>
              <LibPicture source={{ uri: result?.image }} style={{ borderTopLeftRadius: 7, borderTopRightRadius: 7, height: imgHeight, width: imgWidth }} resizeMode="cover" />
            </TouchableOpacity>

            <Text allowFontScaling={false} numberOfLines={1} ellipsizeMode="tail" style={{ marginTop: 10, color: "#000", alignSelf: 'center', textAlign: 'center', fontSize: 20, fontWeight: 'bold' }}> {result?.event_name}</Text>

            <View testID='price_name' style={{ marginTop: 10, borderWidth: 5, padding: 3, borderColor: result?.color, backgroundColor: EventOrder_itemProperty.textColor(result?.color) }}>
              <View style={{ padding: 10, backgroundColor: result?.color, justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
                <EventHtmltext allowFontScaling={false} numberOfLines={3} ellipsizeMode="tail" style={{ color: EventOrder_itemProperty.textColor(result?.color), alignSelf: 'center', textAlign: 'center', fontSize: 20, fontWeight: 'bold' }}> {result?.price_name}</EventHtmltext>
                {
                  result?.ondate != "0000-00-00" &&
                  <Text allowFontScaling={false} style={{ flex: 1, marginRight: 10, marginLeft: 6, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: EventOrder_itemProperty.textColor(result?.color) }}>{moment(result?.ondate).localeFormat("DD MMMM YYYY")}</Text>
                }

              </View>
            </View>

            <View style={{ marginTop: 15, flexDirection: 'row', justifyContent: 'space-between' }} >
              <View style={{ width: 19, height: 19, borderRadius: 9.5, backgroundColor: LibStyle.colorBgGrey, marginLeft: -9.5 }} />
              {/* <Text style={{ marginTop: 5, alignSelf: 'center', fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: "#f39c12" }} ></Text> */}
              <View style={{ width: 19, height: 19, borderRadius: 9.5, backgroundColor: LibStyle.colorBgGrey, marginRight: -9.5 }} />
            </View>

            <View style={{ flexDirection: 'row', margin: 16, justifyContent: 'space-between', marginTop: 0 }}>
              <View style={{ flex: 1 }}>
                {/* <View style={{ flexDirection: 'row' }}> */}
                <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                  <LibIcon name="ticket-outline" size={20} />
                  <Text allowFontScaling={false} style={{ marginLeft: 6, fontFamily: "Arial", fontSize: 30, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{result?.qty}</Text>
                  <Text allowFontScaling={false} style={{ marginLeft: 4, fontFamily: "Arial", fontSize: 16, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{esp.lang("event/order_detail", "ticket")}</Text>
                </View>

                <View style={{ position: 'absolute', right: 0, justifyContent: 'flex-end', alignContent: 'center', alignItems: 'flex-end' }}>
                  {
                    result?.qr != "" && useIndividualQr == 0 &&
                    <TouchableOpacity onPress={() => {
                      showQR?.current?.show()
                    }}>
                      <EventQr_bg>
                        <QRCode ecl="H" size={80} value={result?.qr} />
                      </EventQr_bg>
                    </TouchableOpacity>
                  }
                  {
                    result?.qr == "" && result?.hasOwnProperty("url_sync") && result?.url_sync != "" &&
                    <TouchableOpacity onPress={syncQty} style={{ marginTop: 20, padding: 5, paddingHorizontal: 10, backgroundColor: LibStyle.colorGreen, borderRadius: 7, ...LibStyle.elevation(2) }}>
                      <Text allowFontScaling={false} style={{ color: '#fff', fontWeight: 'bold' }}>{esp.lang("event/order_detail", "show_qr")}</Text>
                    </TouchableOpacity>
                  }
                </View>
                {/* </View> */}
                <UseCondition if={result?.show_ticket_status == 1 && result?.status == 1 || result?.status == 3 || result?.status == 6}>
                  <View style={{ flex: 1, marginRight: LibStyle.width / 4 }}>
                    <Text allowFontScaling={false} style={{ fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, marginBottom: 12, color: "#484848" }}>
                      {
                        result?.qty_used == 0 ? esp.lang("event/order", "have_not_been_used")
                          :
                          result.kind_detail?.everyday_pass == 1 ?
                            "(" + result?.qty_used_today + " " + esp.lang("event/order_detail", "used_today") + ")"
                            :
                            "(" + result?.qty_used + " " + esp.lang("event/order_detail", "used") + ")"
                      }
                    </Text>
                  </View>
                </UseCondition>
                {
                  result?.qty_shared > 0 &&
                  <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 5 }}>
                    <LibIcon name="share-variant-outline" size={20} color='#9b9b9b' />
                    <Text allowFontScaling={false} style={{ marginLeft: 6, fontFamily: "Arial", fontSize: 18, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b" }}>{result?.qty_shared}</Text>
                    <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b" }}>{esp.lang("event/order_detail", "total_share")}</Text>
                  </View>
                }

                {
                  result?.ondate == "0000-00-00" &&
                  <View style={{ marginRight: 85, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                    <LibIcon name="calendar-blank-outline" size={20} />
                    <Text allowFontScaling={false} style={{ flex: 1, marginRight: 10, marginLeft: 6, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{((isInvitationDate || isOnlineWithoutDate) ? esp.lang("event/order_item", "used_once") : dateRange)}</Text>
                  </View>
                }
                {
                  result?.use_seat == 1 &&
                  <View style={{ marginTop: 15, marginRight: 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={{ flexDirection: 'row', flexWrap: 'wrap' }}>
                      {result?.seat_names?.map((item: any, i: number) => {
                        const [front, end] = item?.split("#") || ["", ""];
                        if (item?.includes("#")) {
                          return (
                            <View key={i} style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 5, marginBottom: 7, paddingHorizontal: 5, backgroundColor: '#fff', borderRadius: 5, marginRight: 7, ...LibStyle.elevation(5), }}>
                              <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>
                          );
                        } else {
                          return (
                            <View key={i} style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 5, marginBottom: 7, paddingHorizontal: 5, backgroundColor: '#fff', borderRadius: 5, marginRight: 7, ...LibStyle.elevation(5), }}>
                              <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 20, color: "#000" }}>{item}</Text>
                            </View>
                          )
                        }
                      })}
                    </View>
                  </View>
                }


              </View>
            </View>
            {
              result?.hasOwnProperty('url_addons_booked') && result?.url_addons_booked != "" &&
              <EventOrder_detail_addons_booked addonsBooked={addonsBooked} errorAddonsBooked={errorAddonsBooked} onPress={loadData} />
            }
          </View>

        }
        {
          useIndividualQr > 0 && result?.ticket_codes.length > 0 ?
            <LibCarrousel_snap
              data={result?.ticket_codes}
              style={{ marginVertical: 10, marginBottom: 0, }}
              itemMarginHorizontal={3}
              itemWidth={LibStyle.width - 46}
              maxWidth={LibStyle.width}
              align={"center"}
              renderItem={(item: any, id: any) => {
                return (
                  <View pointerEvents='none' style={{ width: LibStyle.width - 52, flexDirection: 'row', padding: 10, backgroundColor: 'white', borderWidth: 2, borderColor: LibStyle.colorPrimary, borderRadius: 5, overflow: 'hidden', alignItems: 'center' }} >
                    <LibTextstyle textStyle='m_h2' style={{ textAlignVertical: 'center', marginHorizontal: 10 }} text={(id + 1).toString()} />
                    <View style={{ marginLeft: 10, marginVertical: 10, flex: 1, justifyContent: 'flex-start' }} >
                      <LibTextstyle textStyle='headline' numberOfLines={1} text={result?.params?.buyer?.buyer_name} ellipsizeMode='tail' />
                      <LibTextstyle textStyle='caption1' text={result?.params?.buyer?.buyer_email} ellipsizeMode='tail' />
                    </View>
                    <EventQr_bg>
                      <QRCode value={item} size={70} />
                    </EventQr_bg>
                  </View>
                )
              }}
            />
            : null
        }

        <EventAlert
          color={LibStyle.colorRed}
          msg={esp.lang("event/order_detail", "not_allowed_ss", esp.appjson().expo.name)}
          useIcon
          style={{ marginBottom: 0, margin: 15 }}
        />

        <UseCondition if={result?.is_luckydraw && result?.is_luckydraw == 1}>
          <EventButton_order_detail
            color={"#FF6F61"}
            onPress={() => {
              LibNavigation.navigateForResult('event/order_lottery', { id: result?.id }).then(() => {
                loadData()
              })
            }}
            icon={'dice-multiple'}
            title={result?.config_luckydraw != null ? result?.config_luckydraw?.title : esp.lang("event/order_detail", "join_lucky_draw")}
            info={result?.config_luckydraw != null ? result?.config_luckydraw?.subtitle : esp.lang("event/order_detail", "subtitle_lucky_draw")}
          />
        </UseCondition>

        <UseCondition if={result?.is_luckydraw && result?.is_luckydraw == 2}>
          <View style={{ margin: 15, padding: 10, marginBottom: 0, justifyContent: 'center', alignContent: 'center', alignItems: 'center', borderRadius: 7, backgroundColor: LibStyle.colorBgGrey, paddingBottom: 10, ...LibStyle.elevation(3) }}>
            <LibTextstyle textStyle='headline' text={esp.lang("event/order_detail", "already_join_lucky_draw")} style={{ color: '#c9c9c9', fontWeight: 'bold' }} />
          </View>
        </UseCondition>

        <UseCondition if={result?.is_upgradable == 1} >
          <EventButton_order_detail
            color={LibStyle.colorPrimary}
            onPress={() => {
              LibNavigation.navigate('event/order_detail_upgrade', {
                url: result?.url_upgrade,
                dataTicket: result,
              })
            }}
            icon={'chevron-up-circle'}
            title={esp.lang("event/order_detail_upgrade_button", "upgrade")}
            info={esp.lang("event/order_detail_upgrade_button", "eays")}
          />
        </UseCondition>

        {/* tombol add on */}
        {
          result?.hasOwnProperty('url_addons') && result?.url_addons != "" &&
          <LibCollaps
            header={(show) => {
              return (
                <View style={{ margin: 15, alignContent: 'center', alignItems: 'center', paddingHorizontal: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#fff', paddingBottom: 10, paddingTop: 10, flexDirection: 'row' }}>
                  <View style={{ flex: 1 }}>
                    <Text style={{ fontWeight: 'bold', fontSize: 14, color: "#495057" }}>{esp.lang("event/order_detail", "addons")}</Text>
                  </View>
                  <LibIcon name={!show ? "chevron-down" : "chevron-up"} />
                </View>
              )
            }} >
            <EventOrder_detail_addons
              dataTicket={result}
              onPress={(item: any) => {
                const isMultiple = item?.list?.length > 1
                if (isMultiple) {
                  setGroupAddon(item)
                  LibUtils.debounce(() => {
                    dialogAddonList?.current?.show()
                  }, 100)
                } else {
                  if (item?.status == 1) {
                    const addon = item?.list?.[0]
                    setGroupAddon(item)
                    setSelectedAddon(addon)
                    loadDataTicket(result?.id, addon?.price_id, addon?.ondate)
                  }
                }

              }}
            />
          </LibCollaps>
        }

        {/* review */}
        <EventOrder_detail_review dataReview={dataReview} dataTicket={result} />

        {/* view for coupon */}
        {
          result?.url_coupon != "" &&
          <LibCollaps
            show={Number(result?.show_voucher) == 0 ? false : true}
            header={(show) =>
              <View style={{ margin: 15, alignContent: 'center', alignItems: 'center', paddingHorizontal: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#fff', paddingBottom: 10, paddingTop: 10, flexDirection: 'row' }}>
                <View style={{ flex: 1 }}>
                  <Text style={{ fontWeight: 'bold', fontSize: 14, color: "#495057" }}>{esp.lang("event/order_detail", "voucher_or_coupon")}</Text>
                </View>
                <LibIcon name={!show ? "chevron-down" : "chevron-up"} />
              </View>
            }
          >
            <EventOrder_detail_coupon dataTicket={result} />
          </LibCollaps>
        }

        {/* how to use ticket */}
        {
          result?.status == 1 && result?.url_instructions != "" &&
          <LibCollaps
            header={(show) => {
              return (
                <View style={{ margin: 15, alignContent: 'center', alignItems: 'center', paddingHorizontal: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#fff', paddingBottom: 10, paddingTop: 10, flexDirection: 'row' }}>
                  <View style={{ flex: 1 }}>
                    <Text style={{ fontWeight: 'bold', fontSize: 14, color: "#495057" }}>{esp.lang("event/order_detail", "how_to_use")}</Text>
                  </View>
                  <LibIcon name={!show ? "chevron-down" : "chevron-up"} />
                </View>
              )
            }}>
            <EventOrder_detail_instruction dataTicket={result} />
          </LibCollaps>
        }

        {/* term n condition */}
        {
          result?.url_term != "" &&
          <LibCollaps
            header={(show) =>
              <View style={{ margin: 15, alignContent: 'center', alignItems: 'center', paddingHorizontal: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#fff', paddingBottom: 10, paddingTop: 10, flexDirection: 'row' }}>
                <View style={{ flex: 1 }}>
                  <Text style={{ fontWeight: 'bold', fontSize: 14, color: "#495057" }}>{esp.lang("event/order_detail", "tos")}</Text>
                </View>
                <LibIcon name={!show ? "chevron-down" : "chevron-up"} />
              </View>
            }
          >
            <EventOrder_detail_tnc dataTicket={result} />
          </LibCollaps>
        }

        <View style={{ margin: 15, marginBottom: 0, padding: 16, borderRadius: 5, backgroundColor: '#fff' }}>
          <View style={{ alignContent: 'center', alignItems: 'center', justifyContent: 'space-between', flexDirection: 'row' }}>
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "total_bill")}</Text>
            <Text allowFontScaling={false} style={{ alignContent: 'center', alignItems: 'center', fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "right", color: "#9b9b9b" }}>{LibUtils.money(Number(result?.total), curr)}</Text>
          </View>
          <View style={{ alignContent: 'center', alignItems: 'center', justifyContent: 'space-between', flexDirection: 'row', marginTop: 5 }}>
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "booking_code")}</Text>
            <Text allowFontScaling={false} style={{ alignContent: 'center', alignItems: 'center', fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "right", color: LibStyle.colorRed }}>{result?.booking_code}</Text>
          </View>
          {
            result?.status == 1 &&
            <View style={{ justifyContent: 'space-between', flexDirection: 'row', marginTop: 5 }}>
              <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "payment_method")}</Text>
              <Text allowFontScaling={false} style={{ alignContent: 'center', alignItems: 'center', fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "right", color: "#9b9b9b" }}>{result?.payment_title}</Text>
            </View>
          }

          {
            result?.url_ticket != "" &&
            <TouchableOpacity
              onPress={() => {
                LibNavigation.navigate('event/order_detail_visitor', { url: result?.url_ticket, url_addition: result?.url_addition })
              }}
              style={{ ...LibStyle.elevation(2), marginTop: 15, alignContent: 'center', alignItems: 'center', borderWidth: 1, borderColor: LibStyle.colorBgGrey, padding: 10, backgroundColor: '#fff', borderRadius: 5, flexDirection: 'row' }}>
              <View style={{ flex: 1 }}>
                <Text style={{ fontWeight: 'bold', fontSize: 14, color: "#495057" }}>{esp.lang("event/order_detail", "buyer_detail")}</Text>
              </View>
              <LibIcon name={"chevron-right"} />
            </TouchableOpacity>
          }
        </View>


        {
          esp.isDebug("") &&
          <View style={{ padding: 5, marginTop: 15 }}>
            <EventButton label={esp.lang("event/order_detail", "send_to_email")} onPress={() => {
              LibToastProperty.show("Coming Soon")
            }} backgroundColor={"#FFF"} borderColor={LibStyle.colorGreen} fontColor={LibStyle.colorGreen} />
          </View>
        }

      </LibScroll >

      {/* untuk share ke */}
      {
        result?.par_id == 0 && result?.status == 1 && result?.is_shareable == 1 && result?.qty_shareable > 0 &&
        <View style={{ padding: 5, }}>
          <EventButton label={Number(result.is_shareable) ? /*share_ticket*/esp.lang("event/order_detail", "share_ticket") : esp.lang("event/order_detail", "shared")} onPress={() => {
            if (Number(result.is_shareable)) {
              LibDialog.confirm(esp.lang("event/order_detail", "share_title"), esp.lang("event/order_detail", "share_msg", esp.appjson().expo.name), esp.lang("event/order_detail", "share_ok"), () => {
                LibNavigation.navigate('event/order_detail_share', { url: url })
              }, esp.lang("event/order_detail", "share_no"), () => {

              })
            }
          }} backgroundColor={Number(result.is_shareable) ? LibStyle.colorGreen : LibStyle.colorLightGrey} />
        </View>
      }

      {/* untuk mengembalikan tiket  */}
      {
        result?.par_id != 0 && result?.status == 1 && result?.qty_returnable > 0 &&
        <View style={{ padding: 5 }}>
          <EventButton label={esp.lang("event/order_detail", "return_ticket")} onPress={() => {
            LibNavigation.navigate('event/order_detail_return', { url: url })
          }} backgroundColor={LibStyle.colorGreen} />
        </View>
      }

      <LibSlidingup ref={showQR}>
        <View style={{ backgroundColor: 'white', borderTopRightRadius: 20, borderTopLeftRadius: 20, padding: 10 }}>
          <View style={{ margin: 10, alignSelf: 'center' }}>
            {
              result?.qr != "" &&
              <EventQr_bg>
                <QRCode ecl="H" size={200} value={result?.qr} />
              </EventQr_bg>
            }
          </View>
          <Text allowFontScaling={false} style={{ padding: 15, paddingBottom: 0, alignSelf: 'center', fontFamily: "Arial", fontSize: 18, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0 }}>{result?.booking_code}</Text>
        </View>
      </LibSlidingup>

      <LibSlidingup ref={dialogQtyAddons}>
        <View style={{ backgroundColor: 'white', maxHeight: LibStyle.height - (LibStyle.height / 3), borderTopRightRadius: 20, borderTopLeftRadius: 20, padding: 20 }}>
          <Text style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", color: "#b7b7b7" }} >{esp.lang("event/order_detail", "addons")}</Text>
          <Text style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", color: "#4a4a4a" }} >{getSelectedAddon()?.title}</Text>
          {
            getSelectedAddon()?.info != "" &&
            <EventHtmltext style={{ fontFamily: "Arial", marginBottom: 10, fontSize: 12, marginLeft: 10, color: "#b7b7b7" }} >{getSelectedAddon()?.info}</EventHtmltext>
          }

          <ScrollView>
            <Text allowFontScaling={false} style={{ marginVertical: 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("#") || ["", ""];
                let colorDisable = item?.status == 0 ? LibStyle.colorBgGrey : "#f1f1f1"
                let colorAccent = item?.checked == 1 ? LibStyle?.colorGreen : colorDisable
                return (
                  <TouchableOpacity key={i} onPress={() => {
                    if (item?.status == 1) {
                      let a = LibObject.set(dataTicket, item.checked == 1 ? 0 : 1)(i, 'checked')
                      setDataTicket(a)
                    }

                  }} style={{ padding: 10, marginBottom: 10, borderRadius: 4, backgroundColor: item?.status == 1 ? "#fff" : LibStyle.colorBgGrey, borderColor: colorAccent, borderWidth: 1, flexDirection: 'row' }}>
                    <View style={{ flex: 5 }}>
                      <Text allowFontScaling={false} style={{ fontSize: 14, fontStyle: "normal", color: "#000", fontWeight: "bold", }}>{result?.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: "#b7b7b7" }}>{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={{ marginTop: 5 }}>
                          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#b7b7b7" }}>{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={colorAccent} />
                    </View>
                  </TouchableOpacity>
                )
              })
            }
          </ScrollView>

          <EventButton label={esp.lang("event/order_detail", "next")} onPress={() => {
            if (valid) {
              dialogQtyAddons?.current?.hide()
              loadDataAddons(getSelectedAddon()?.addons_id, getSelectedAddon()?.url)
            }
          }}
            backgroundColor={!valid ? LibStyle.colorGrey : LibStyle.colorGreen}
          />
        </View>
      </LibSlidingup>

      {/* add on list */}
      <LibSlidingup ref={dialogAddonList}>
        <View style={{ backgroundColor: 'white', borderTopRightRadius: 20, maxHeight: LibStyle.height / 2, borderTopLeftRadius: 20, paddingBottom: 20 }}>
          <View style={{ margin: 15, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
            <Text allowFontScaling={false} style={{ flex: 1, fontSize: 16, fontWeight: 'bold' }}>{getGroupAddon()?.hasOwnProperty("list") ? getGroupAddon()?.title : getGroupAddon()?.group_title}</Text>
            <TouchableOpacity style={{ flex: 1, alignItems: 'flex-end' }} onPress={() => dialogAddonList?.current?.hide()}>
              <LibIcon name='close' />
            </TouchableOpacity>
          </View>
          <ScrollView>
            {/* ini list untuk yang ondate */}
            {
              getGroupAddon()?.list?.length > 0 && getGroupAddon()?.list?.map((item: any, i: number) => {
                return (
                  <EventButton_order_detail
                    disable={item?.hasOwnProperty('status') && item.status == 0 ? true : false}
                    status_message={item?.status_message}
                    key={i}
                    color={result?.color}
                    onPress={() => {
                      if (item?.hasOwnProperty('status') && item?.status == 1) {
                        setSelectedAddon(item)
                        dialogAddonList?.current?.hide()
                        loadDataTicket(result?.id, item?.price_id, item?.ondate)
                        // loadDataAddons(getGroupAddon()?.addons_id, item?.url)
                      }
                    }}
                    icon={'plus-circle-outline'}
                    title={item?.title}
                    subtitle={item?.ondate != "0000-00-00" ? LibUtils.moment(item.ondate).format("DD MMM YYYY") : ''}
                    info={item?.info}
                  />
                )
              })
            }
          </ScrollView>
        </View>
      </LibSlidingup>

    </View >
  )
}

export interface ItemTiket {
  booking_id: string;
  id: string;
  ticket_code: string;
  name: string;
  email: string;
  phone: string;
  status: string;
}
