// 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 { EventReviewProperty } from 'esoftplay/cache/event/review/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 { UserClass } from 'esoftplay/cache/user/class/import';

import { applyStyle } from 'esoftplay';
import { EventAlert } from 'esoftplay/cache/event/alert/import';
import { EventHtmltext } from 'esoftplay/cache/event/htmltext/import';
import { EventIndexProperty } from 'esoftplay/cache/event/index/import';
import { EventOrder_detail_upgrade_button } from 'esoftplay/cache/event/order_detail_upgrade_button/import';
import { EventPopup } from 'esoftplay/cache/event/popup/import';
import { EventQr_bg } from 'esoftplay/cache/event/qr_bg/import';
import { EventRating } from 'esoftplay/cache/event/rating/import';
import { EventSecure_page } from 'esoftplay/cache/event/secure_page/import';
import { EventStep } from 'esoftplay/cache/event/step/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 { Linking, Pressable, Text, TouchableOpacity, View } from 'react-native';
import QRCode from 'react-native-qrcode-svg';


export interface EventOrder_detailProps {
  navigation: any
}


function renderTermItem(item: any, i: number) {
  return (
    <View key={i}>
      <EventStep text={item} />
    </View>
  )
}


let urlsInstruction: any[] = []

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

function getStringReview(data: any) {
  const groupedData = data.reduce((acc: any[], obj: any) => {
    const { survey_id, survey_question, survey_option, content } = obj;

    if (!acc[survey_id]) {
      acc[survey_id] = {
        survey_id,
        survey_question,
        values: []
      };
    }

    if (survey_option) {
      acc[survey_id].values.push(survey_option);
    }
    if (content) {
      acc[survey_id].values.push(content);
    }

    return acc;
  }, {});

  const finalResult = Object.values(groupedData).map((group: any) => {
    const { survey_question, values } = group;
    const valuesString = values.join(", ");
    return `\nQ: ${survey_question}\nA: ${valuesString}`;
  })
  return finalResult
}



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

  EventSecure_page()
  const [user] = UserClass.state().useState()

  let showQR = useRef<LibSlidingup>(null)
  const dialogSendBack = 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 [tickets, setTickets] = useSafeState(result?.detail_ticket?.tickets ?? [])
  const useIndividualQr = result?.config?.use_individual_qr_ticket

  const dataTickets = tickets?.filter?.((x: ItemTiket) => x?.email == user?.email && x?.ticket_code != '')

  const [coupons, setCoupons] = useSafeState<any>()
  const [qty, setQty] = useSafeState<number>(1)

  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)

  urlsInstruction = []
  result?.instructions?.map?.((item: any) => {
    let matches = item.match(/(https?:\/\/[^\s]+)/g);
    if (matches) {
      urlsInstruction.push(...matches)
    }
  })


  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)
      // esp.log(res);

      new LibCurl(res?.url_coupon, null, (ress: any) => {
        setCoupons(ress)
      }, (error: any) => {
        // setEmptyCoupons(error)
      })

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

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

      // // load data untuk upgrade tiket
      // if (res?.is_upgradable == 1) {
      //   loadDataUpgradeTicket(res?.url_upgrade)
      // }

      new LibCurl(res?.url_ticket, null,
        (res: any, msg: string) => {
          setTickets(res.tickets)
        }, (err: any) => {
          LibToastProperty.show(err.message)
        }
      )

    }, (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()
    })
  }

  useEffect(() => {
    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)
  }

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

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

  function doCancel(url: string): void {
    LibDialog.warningConfirm(esp.lang("event/order_detail", "confirm"), esp.lang("event/order_detail", "cancel_this_order"), esp.lang("event/order_detail", "btn_yes"), () => {
      LibProgress.show(esp.lang("event/order_detail", "please_wait"))
      new LibCurl(url, null, (result: any, msg: any) => {
        LibProgress.hide()
        LibNavigation.back()
      }, (error: any) => {
        LibDialog.warning(esp.lang("event/order_detail", "cancel_err"), error?.message);
        LibProgress.hide()
      }, 1)
    }, esp.lang("event/order_detail", "btn_cancel"), () => {

    })
  }

  function addReturn(): void {
    if (qty < Number(result.qty_returnable)) {
      setQty(qty + 1)
    }
  }

  function minReturn(): void {
    setQty(qty == 1 ? 1 : qty - 1)
  }

  function sendBack() {
    LibDialog.confirm(esp.lang("event/order_detail", "warning"), esp.lang("event/order_detail", "return_this_ticket"), esp.lang("event/order_detail", "btn_yes"), () => {
      LibProgress.show(esp.lang("event/order_detail", "please_wait"))
      new LibCurl('event_booking_shared_return?booking_id=' + result?.id + '&qty_shared=' + qty, null, (res: any, msg: any) => {
        // LibNotify(res)
        LibProgress.hide()
        LibDialog.info(esp.lang("event/order_detail", "information"), msg)
        LibNavigation.back()
      }, (error: any) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/order_detail", "back_err"), error?.message);
        LibNavigation.back()
      }, 1)
    }, esp.lang("event/order_detail", "btn_cancel"), () => { })
  }

  if (result == undefined && !coupons) {
    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 (
      <View style={{ flex: 1, backgroundColor: '#f6f6f6' }}>
        <EventHeader title={esp.lang("event/order_detail", "order_detail")} />
        <View style={[{ margin: 18, borderTopLeftRadius: 7, borderTopRightRadius: 7, backgroundColor: '#fff', paddingBottom: 10 }, LibStyle.elevation(3)]}>

          <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>
          <View style={{ flexDirection: 'row', margin: 14, marginTop: 4, justifyContent: 'space-between' }}>
            <View style={{ marginTop: 14 }}>
              <EventHtmltext allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{esp.lang("event/order_detail", "ticket")}{result?.price_name}</EventHtmltext>
              <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>
              <UseCondition if={result?.show_ticket_status == 1 && result?.status == 1 || result?.status == 3 || result?.status == 6}>
                <Text allowFontScaling={false} style={{ fontSize: 12, fontWeight: "normal", fontStyle: "normal", flexWrap: 'wrap', 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>
              </UseCondition>
              <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                <LibIcon name="calendar-blank-outline" size={20} />
                <Text allowFontScaling={false} style={{ marginLeft: 6, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{result?.ondate != "0000-00-00" ? moment(result?.ondate).localeFormat("DD MMMM YYYY") : ((isInvitationDate || isOnlineWithoutDate) ? esp.lang("event/order_item", "used_once") : dateRange)}</Text>
              </View>
            </View>
            {
              result?.status == "1" &&
              <View style={{ marginTop: 14, justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
                {
                  result?.qr != "" &&
                  <TouchableOpacity onPress={() => {
                    result?.status == "1" && showQR?.current?.show()
                  }}>
                    <EventQr_bg>
                      <QRCode ecl="H" size={80} value={result?.qr} />
                    </EventQr_bg>
                  </TouchableOpacity>
                }
              </View>
            }
          </View>

          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }} >
            <View style={{ width: 19, height: 19, borderRadius: 9.5, backgroundColor: "#f6f6f6", 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: "#f6f6f6", marginRight: -9.5 }} />
          </View>

          <View style={{ margin: 14, flexDirection: 'row' }}>
            <Text style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorRed }} >{result?.reschedule_notes}</Text>
          </View>
          {
            result?.par_id > 0 ?
              null
              :
              <EventButton onPress={() => {
                LibNavigation.navigate('event/order_reschedule', { url: result?.url_reschedule })
              }} label={result?.is_refundable == 1 ? esp.lang("event/order_detail", "refund_rescedule") : esp.lang("event/order_detail", "rescedule")} backgroundColor={LibStyle.colorGreen} style={{ marginLeft: 20, marginRight: 20, marginBottom: 10 }} />
          }
        </View>
      </View>
    )
  }

  let startEvent = result?.start_date + " " + result?.start_time
  let dateNow = LibUtils.moment().localeFormat("YYYY-MM-DD HH:mm")

  const termData = result?.term ? Object.values(result?.term) : []

  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>
              </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', 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>
                <UseCondition if={result?.show_ticket_status == 1 && result?.status == 1 || result?.status == 3 || result?.status == 6}>
                  <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>
                </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>
                }

                <View style={{ 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" }}>{result?.ondate != "0000-00-00" ? moment(result?.ondate).localeFormat("DD MMMM YYYY") : ((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' }}>
                      {
                        tickets?.map((item: any, i: number) => {
                          return (
                            <View key={i} style={{ paddingVertical: 5, marginBottom: 7, paddingHorizontal: 7, borderWidth: 1, borderColor: '#000', backgroundColor: '#fff', borderRadius: 5, marginRight: 7 }}>
                              <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 20, color: '#000' }}>{item.seat_name}</Text>
                            </View>
                          )
                        })
                      }
                    </View>
                  </View>
                }

              </View>
              <View style={{ marginTop: 14, justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
                {
                  result?.qr != "" && useIndividualQr == 0 &&
                  <TouchableOpacity onPress={() => {
                    showQR?.current?.show()
                  }}>
                    <EventQr_bg>
                      <QRCode ecl="H" size={80} value={result?.qr} />
                    </EventQr_bg>
                  </TouchableOpacity>
                }
              </View>
            </View>

          </View>
        }
        {
          useIndividualQr > 0 && dataTickets.length > 0 ?
            <LibCarrousel_snap
              data={dataTickets}
              style={{ marginVertical: 10, marginBottom: 0, }}
              itemMarginHorizontal={3}
              itemWidth={LibStyle.width - 46}
              maxWidth={LibStyle.width}
              align={"center"}
              renderItem={(item: ItemTiket, 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={item.name} ellipsizeMode='tail' />
                      <LibTextstyle textStyle='caption1' text={item.email} ellipsizeMode='tail' />
                    </View>
                    <EventQr_bg>
                      <QRCode value={item.ticket_code} size={70} />
                    </EventQr_bg>
                  </View>
                )
              }}
            />
            : null
        }

        <EventAlert
          color="#FFC523"
          msg={esp.lang("event/order_detail", "not_allowed_ss")}
          useIcon
          style={{ marginBottom: 0, margin: 15 }}
        />

        <UseCondition if={result?.is_luckydraw && result?.is_luckydraw == 1}>
          <TouchableOpacity onPress={() => {
            LibNavigation.navigateForResult('event/order_lottery', { id: result?.id }).then(() => {
              loadData()
            })
          }} style={{ margin: 15, padding: 10, marginBottom: 0, justifyContent: 'center', alignContent: 'center', alignItems: 'center', borderRadius: 7, backgroundColor: LibStyle.colorGreen, paddingBottom: 10 }}>
            <LibTextstyle textStyle='headline' text={esp.lang("event/order_detail", "join_lucky_draw")} style={{ color: '#fff', fontWeight: 'bold' }} />
          </TouchableOpacity>
        </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} >
          <EventOrder_detail_upgrade_button onPress={() => {
            LibNavigation.navigate('event/order_detail_upgrade', {
              url: result?.url_upgrade,
              dataTicket: result,
            })
          }} />
        </UseCondition>

        {
          // jika mau edit view dibawah ini, tekan ctrl + f terus paste prefik dibawah ini
          // view_reviewed
          dataReview?.status == 1 ?
            <View style={{ margin: 15, marginBottom: 0, borderRadius: 7, backgroundColor: 'white', padding: 10 }}>
              <View style={{ flexDirection: 'row', alignItems: 'flex-start', marginTop: 10 }}>
                <LibPicture source={{ uri: user?.image }} style={{ height: 50, width: 50, borderRadius: 25 }} />
                <View style={{ marginLeft: 10, flex: 1 }}>
                  <Text allowFontScaling={false} numberOfLines={1} ellipsizeMode='tail' style={{ fontSize: 16, fontWeight: 'bold' }}>{user?.name}</Text>
                  <Text allowFontScaling={false} style={{ fontSize: 12, color: '#c9c9c9' }}>{LibUtils.moment(dataReview?.review?.created).localeFormat("D MMM YYYY")}</Text>
                  <View style={{ marginTop: 5 }}>
                    <EventRating disabled onChangeRating={() => { }} defaultValue={dataReview?.review?.rating} size={18} containerStyle={{ padding: 0, justifyContent: 'flex-start' }} />
                    {
                      dataReview?.review?.content != "" &&
                      <Text allowFontScaling={false} style={{ marginTop: 10, fontSize: 12, color: '#000' }}>{dataReview?.review?.content.replace(/\\n/g, '\n')}</Text>
                    }
                    {
                      dataReview?.surveys?.length > 0 &&
                      getStringReview(dataReview?.surveys).map((sur) => (
                        <Text allowFontScaling={false} style={{ fontSize: 12, color: '#000' }}>{sur}</Text>
                      ))
                    }
                  </View>
                </View>
              </View>
              {
                dataReview?.status == 2 &&
                <View style={applyStyle({ borderColor: '#FC9722', backgroundColor: '#FDF1DE', borderWidth: 1, borderStyle: 'dashed', borderRadius: 5, padding: 5, marginTop: 15, marginBottom: 0 })} >
                  <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" })}>{esp.lang("event/order_detail", "thanks")}</Text>
                </View>
              }

            </View>
            :
            dateNow > startEvent ?
              <View style={{ margin: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#000', padding: 10 }}>
                {
                  dataReview?.review == null ?
                    <Pressable>
                      <EventRating onChangeRating={(rate) => {
                        let type = EventReviewProperty.calculateProb(result?.config?.review)
                        let urlForm = "event_order_detail_review_form?id=" + result?.id + "&type=" + type?.type
                        let args = {
                          url_form: urlForm,
                          type: type?.type,
                          booking_id: result?.id,
                          rate: rate
                        }
                        if (result?.review_status != 1) {
                          LibNavigation.navigate('event/review_add', args)
                        }
                      }} defaultValue={5} size={50} containerStyle={{ padding: 0, backgroundColor: 'transparent' }} />
                      <Text allowFontScaling={false} style={{ alignSelf: 'center', marginTop: 15, fontSize: 18, fontWeight: 'bold', color: '#fff' }}>{esp.lang("event/order_detail", "leave_review")}</Text>
                      <Text allowFontScaling={false} style={{ alignSelf: 'center', marginTop: 7, fontSize: 14, color: '#fff' }}>{esp.lang("event/order_detail", "review_info")}</Text>

                    </Pressable>
                    :
                    // view_reviewed
                    <View style={{ margin: -10, backgroundColor: '#fff', padding: 10, borderRadius: 7 }}>
                      <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                        <LibPicture source={{ uri: user?.image }} style={{ height: 50, width: 50, borderRadius: 25 }} />
                        <View style={{ marginLeft: 10 }}>
                          <Text allowFontScaling={false} numberOfLines={1} ellipsizeMode='tail' style={{ fontSize: 16, fontWeight: 'bold' }}>{user?.name}</Text>
                          <Text allowFontScaling={false} style={{ fontSize: 12, color: '#c9c9c9' }}>{LibUtils.moment(dataReview?.review?.created).localeFormat("D MMM YYYY")}</Text>
                          <View style={{ marginTop: 5 }}>
                            <EventRating disabled onChangeRating={() => { }} defaultValue={dataReview?.review?.rating} size={18} containerStyle={{ padding: 0, backgroundColor: 'transparent' }} />
                          </View>
                        </View>
                      </View>

                      <Text allowFontScaling={false} numberOfLines={5} ellipsizeMode='tail' style={{ marginTop: 10, fontSize: 12, color: '#000' }}>{dataReview?.review?.content}</Text>
                      {
                        dataReview?.status == 2 &&
                        <View style={applyStyle({ borderColor: '#FC9722', backgroundColor: '#FDF1DE', borderWidth: 1, borderStyle: 'dashed', borderRadius: 5, padding: 5, marginTop: 15, marginBottom: 0 })} >
                          <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" })}>{esp.lang("event/order_detail", "thanks")}</Text>
                        </View>
                      }
                    </View>
                }
              </View>
              : null
        }

        {/* view for coupon */}
        {
          result?.status != "2" && coupons &&
          <View style={{ margin: 15, marginBottom: 0, borderRadius: 7, backgroundColor: '#fff', paddingBottom: 10, paddingTop: 10 }}>
            <View style={{ marginHorizontal: 20 }}>
              <Text style={{ fontWeight: 'bold', fontSize: 14, color: LibStyle.colorPrimary }}>{coupons.title || ''}</Text>
            </View>

            {
              coupons?.list?.map((item: any, i: number) => {
                return (
                  <TouchableOpacity key={i} onPress={() => {
                    esp.modProp("event/coupon").getCouponDetail(item?.url_detail_coupon)
                  }} style={[{ marginBottom: 4, margin: 15, borderRadius: 15, backgroundColor: '#fff' }, LibStyle.elevation(2)]}>
                    <LibPicture source={{ uri: item.image }} resizeMode="cover" style={{ height: (LibStyle.width - 60) * 0.43, width: LibStyle.width - 60, borderRadius: 5 }} />
                    <View style={{ position: 'absolute', top: (((LibStyle.width - 60) * 0.43) / 2) - 10, marginBottom: 15, flexDirection: 'row', justifyContent: 'space-between' }} >
                      <View style={{ width: 23, height: 23, borderRadius: 11.5, backgroundColor: "white", marginLeft: -9.5 }} />
                      <View style={{ flex: 1 }} />
                      <View style={{ width: 23, height: 23, borderRadius: 11.5, backgroundColor: "white", marginRight: -9.5 }} />
                    </View>
                  </TouchableOpacity>
                )
              })
            }

            {
              coupons?.pages > 1 &&
              <TouchableOpacity onPress={() => {
                LibNavigation.navigate("event/coupon")
              }}>
                <View style={{ marginTop: 10, alignContent: 'center', alignItems: 'center', justifyContent: 'center', backgroundColor: LibStyle.colorPrimary, height: 50 }}>
                  <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", textAlign: 'center', fontStyle: "normal", letterSpacing: 0, color: "#fff" }}>{esp.lang("event/order_detail", "see_all_coupon")}</Text>
                </View>
              </TouchableOpacity>
            }
          </View>
        }

        <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>
          }
        </View>

        {
          result?.status == 1 && result?.instructions?.length > 0 &&
          <View style={{ margin: 15, marginBottom: 5, padding: 16, borderRadius: 5, backgroundColor: '#fff' }}>
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "how_to_use")}</Text>
            {
              result?.instructions.map((item: any, i: number) => {
                const urls = item.match(/(https?:\/\/[^\s]+)/g)
                const text = item.replace(urls?.[0], '~:::~')
                const texts = text.split('~:::~')
                return (
                  <TouchableOpacity key={i + 1} onPress={() => {
                    if (item.match(/(https?:\/\/[^\s]+)/g)) {
                      Linking.openURL(urls[0])
                    }
                  }}>
                    <Text allowFontScaling={false} style={{ flexWrap: 'wrap', marginBottom: 5, fontSize: 14, fontWeight: "normal", fontStyle: "normal", lineHeight: 18, color: "#4a4a4a", marginTop: 4 }}>
                      {texts?.[0]}
                      {urls && <Text allowFontScaling={false} style={{ flexWrap: 'wrap', marginBottom: 5, fontSize: 14, fontWeight: "normal", fontStyle: "normal", lineHeight: 18, color: LibStyle.colorBlue, marginTop: 4 }}>{urls[0]}</Text>}
                      {texts?.[1]}
                    </Text>
                  </TouchableOpacity>
                )
              })
            }

            {
              urlsInstruction.length > 0 && urlsInstruction.map((item: any, i: number) => {
                return (
                  <View key={i + 1} style={{ padding: 10, marginTop: 10, flexDirection: 'row-reverse' }}>
                    <TouchableOpacity onPress={() => {
                      LibUtils.share(item)
                    }} style={{ ...LibStyle.elevation(5), alignContent: 'center', alignItems: 'center', justifyContent: 'center', backgroundColor: LibStyle.colorPrimary, height: 40, width: 40, borderRadius: 20, marginHorizontal: 10 }}>
                      <LibIcon color="#fff" name="share" />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => {
                      LibUtils.copyToClipboard(item)
                      LibToastProperty.show(esp.lang("event/order_detail", "copied"))
                    }} style={{ ...LibStyle.elevation(5), alignContent: 'center', alignItems: 'center', justifyContent: 'center', backgroundColor: LibStyle.colorPrimary, height: 40, width: 40, borderRadius: 20, marginHorizontal: 10 }}>
                      <LibIcon color="#fff" name="content-copy" />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => {
                      Linking.openURL(item)
                    }} style={{ ...LibStyle.elevation(5), alignContent: 'center', alignItems: 'center', justifyContent: 'center', backgroundColor: LibStyle.colorPrimary, height: 40, width: 40, borderRadius: 20, marginHorizontal: 10 }}>
                      <LibIcon.MaterialIcons color="#fff" name="open-in-browser" />
                    </TouchableOpacity>
                  </View>
                )
              })
            }

          </View>
        }
        {
          termData?.length > 0 &&
          <View style={{ margin: 16, borderRadius: 5, padding: 10, backgroundColor: 'white' }} >
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "tos")}</Text>
            {termData?.map(renderTermItem)}
          </View>
        }
        {
          result?.url_ticket != "" &&
          <TouchableOpacity onPress={() => {
            LibNavigation.navigate('event/order_detail_visitor', { url: result?.url_ticket, url_addition: result?.url_addition })
          }} style={{ ...LibStyle.elevation(3), margin: 15, padding: 16, borderRadius: 5, backgroundColor: '#fff', flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "buyer_detail")}</Text>
            <LibIcon name='chevron-right-circle-outline' size={30} color={LibStyle.colorBlue} />
          </TouchableOpacity>
        }

        {
          esp.isDebug("") &&
          <View style={{ padding: 5 }}>
            <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.lang("event/order_detail", "share_ok"), () => {
                LibNavigation.navigate('event/order_share_to', { 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={() => {
            dialogSendBack?.current?.show()
          }} 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={dialogSendBack} >
        <View style={{ backgroundColor: 'white', borderTopLeftRadius: 20, borderTopRightRadius: 20, padding: 20 }} >
          <EventPopup email={result?.sharer_email?.trim?.()} redirect={() => {
            if (result?.use_seat == 1) {
              let data = {
                qty: qty
              }
              LibNavigation.navigate('event/seat', {
                url: result?.url_ticket,
                dataTicket: data,
                returnTicket: true,
              })
            } else {
              sendBack()
            }
            dialogSendBack.current!.hide()
          }} cancel={() => {
            dialogSendBack.current!.hide()
          }}
            view={
              <View style={{ flexDirection: 'row', marginTop: 20, marginBottom: 8, justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
                <TouchableOpacity onPress={() => { minReturn() }}>
                  <View style={{ width: 28, height: 28, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center' }}>
                    <LibIcon name="minus" color="#e74c3c" />
                  </View>
                </TouchableOpacity>
                <Text style={{ fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b", marginLeft: 13, marginRight: 13 }}>{qty}</Text>
                <TouchableOpacity onPress={() => { addReturn() }}>
                  <View style={{ width: 28, height: 28, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center' }}>
                    <LibIcon name="plus" color="#16a085" />
                  </View>
                </TouchableOpacity>
              </View>
            }
          />

        </View>
      </LibSlidingup>

    </View >
  )
}

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