// withHooks
import { applyStyle } from 'esoftplay';
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/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 { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibSkeleton } from 'esoftplay/cache/lib/skeleton/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 { UseDeeplinkProperty } from 'esoftplay/cache/use/deeplink/import';
import esp from 'esoftplay/esp';
import useLazyState from 'esoftplay/lazy';
import useSafeState from 'esoftplay/state';
import { useEffect, useRef } from 'react';

import { EventAlert } from 'esoftplay/cache/event/alert/import';
import { EventConfigProperty } from 'esoftplay/cache/event/config/import';
import { EventCountdown_event } from 'esoftplay/cache/event/countdown_event/import';
import { EventHtmltext } from 'esoftplay/cache/event/htmltext/import';
import { EventLoading_pageProperty } from 'esoftplay/cache/event/loading_page/import';
import { EventOrder_itemProperty } from 'esoftplay/cache/event/order_item/import';
import { EventQueue, EventQueueProperty } from 'esoftplay/cache/event/queue/import';
import { UseCondition } from 'esoftplay/cache/use/condition/import';
import { UseTasks } from 'esoftplay/cache/use/tasks/import';
import moment from 'esoftplay/moment';
import React from 'react';
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventTicket_list2Args {

}
export interface EventTicket_list2Props {

}

type Result = {
  "id": string,
  "title": string,
  "image": string,
  "images": Array<{
    "image": string,
    "title": string,
    "description": string,
  }>,
  "image_map": string,
  "charge_payment": number,
  "status": string,
  "quota_checkout": string,
  "show_price": string,
  "countdown_booking": string,
  "config_queue": {
    "limit": number,
    "time": number,
  },
  "form_allotment": string,
  "form_allotment_text": string,
  "use_queue": string,
  "is_pod_limit": string,
  "event_tag": [],
  "charge_payment_type": string,
  "price_type": Array<{
    "price_id": string,
    "type": string,
    "kind": string,
    "currency": string,
    "price_min": string,
    "price_max": string,
    "use_code": string,
    "use_seat": string,
    "use_quota": boolean,
    "config": {
      "seat_autopick": string,
      "seat_autopick_start": string,
    },
    "price_date": string,
    "info": string,
    "qty_min": string,
    "qty_max": string,
    "tax": string,
    "quota": string,
    "quota_used": string,
    "status": number,
    "quota_checkout": string,
    "date_start": string,
    "date_end": string,
    "paper_size": string,
    "is_refundable": boolean,
    "refund": string,
    "is_printed": string,
    "image_map": string,
    "term": Array<string>,
    "list": Array<{
      "list_id": string,
      "date_id": number,
      "ondate": string,
      "price_id": string,
      "price": string,
      "quota": string,
      "quota_used": string,
      "show_limit": number,
      "status": number,
      "show_price": number,
      "currency": string,
      "schedule": {
        "info": string,
        "artist": [],
      },
      "is_available"?: string,
    }>,
  }>,
  "price_type_info": string,
  "exhibitor": {
    "list": Array<{
      "id": string,
      "title": string,
      "image": string,
    }>,
    "more_url": string,
  },
  "url_share": string,
  "url_price_config": string
}

const taskSeat = UseTasks()
const taskAdditional = UseTasks()

export default function m(props: EventTicket_list2Props): any {
  const [pendingData] = EventLoading_pageProperty.state().useState()

  const { url, is_multiprice, fee_platform, subscribed, show_fee_percentage }: any = useRef(LibNavigation.getArgsAll(props)).current

  const [deeplinkParams] = UseDeeplinkProperty.params.useState()

  const [unAvailableResult, setUnavailableResult] = useLazyState<any>()
  const [, setHasAdditionGlobal, getHasAdditionGlobal] = useLazyState<any>()
  const [availableResult, setAvailableResult, getAvailableResult] = useSafeState<any>()
  const [, setDataPostBooking, getDataPostBooking] = useLazyState<any>([])
  const [dataAddition, setDataAddition] = useSafeState<any>([])
  const [isPass, setIsPass] = useSafeState(true)
  const [showAll, setShowAll] = useSafeState<any>({});
  const [urlPayment, setUrlPayment] = useLazyState<any>()
  const [loading, setLoading] = useSafeState<boolean>(false)

  let dataEvent: any = {
    event_id: availableResult?.id,
    event_title: availableResult?.title,
    charge_payment: availableResult?.charge_payment,
    charge_payment_type: availableResult?.charge_payment_type,
    images: availableResult?.images,
  }

  const [ticketSeat, resetTicketSeat] = taskSeat((item: any) => new Promise((next) => {
    if (item.use_seat == 1) {
      if (item.adjacent_seats == undefined || item.adjacent_seats == 0) {
        LibNavigation.navigateForResult('event/seat_map_new', {
          url: 'event_seat',
          dataTicket: {
            ...dataEvent,
            qty: item.qty,
            selected_ticket: {
              price_id: item.price_id,
              type: item.type,
              list: {
                ondate: item.ondate
              }
            }
          },
          show_fee_percentage
        }, item.list_id)
          .then((value: any) => {
            const merged = { ...item, ...value }
            let a = LibObject.replaceItem(getDataPostBooking(), (it) => it.list_id == item.list_id, merged)()
            setDataPostBooking(a)
            next()
          })
      } else {
        let a = LibObject.replaceItem(getDataPostBooking(), (it) => it.list_id == item.list_id, item)()
        setDataPostBooking(a)
        next()
      }
    } else {
      let a = LibObject.replaceItem(getDataPostBooking(), (it) => it.list_id == item.list_id, item)()
      setDataPostBooking(a)
      next()
    }
  }), () => {

    // bagian iki di remake

    const transformedData: any[] = [];
    availableResult?.price_type?.filter((y: any) => y.selected == 1)?.map((item: any) => {
      item?.list?.filter((x: any) => x.selected == 1)?.map((listItem: any) => {
        transformedData.push({
          ...item,
          list_id: listItem.list_id,
          qty: listItem.qty,
          ondate: listItem.ondate,
          list: [listItem],
        });
      });
    })


    if (getHasAdditionGlobal() == 1) {
      LibNavigation.navigateForResult('event/additional', {
        event_id: dataEvent?.event_id,
        qty: 1,
      }, 696).then((value) => {
        if (value != "") {
          setDataAddition(dataAddition.push(JSON.parse(value)))
        }
        resetTicketAdditional()
        ticketAdditional(transformedData)
      })

    } else {
      resetTicketAdditional()
      ticketAdditional(transformedData)
      setDataAddition([])
    }

  })


  const [ticketAdditional, resetTicketAdditional] = taskAdditional((item: any) => new Promise((next) => {
    if (item.has_addition && item.has_addition == 1) {
      LibNavigation.navigateForResult('event/additional', {
        event_id: dataEvent?.event_id,
        qty: item.qty,
        ondate: item.ondate,
        data: dataEvent,
        price_id: item.price_id,
        type_ticket: item.type
      }, item.list_id).then((value) => {
        if (value != "") {
          setDataAddition(dataAddition.push(JSON.parse(value)))
        }
        next()
      })
    } else {
      next()
    }
  }), () => {
    if (dataAddition?.length > 0) {
      dataEvent.addition = dataAddition
    }

    const selectedPriceIds = getDataPostBooking().filter((x: any) => x.selected == 1).map((x: any) => x.price_id)

    curlPriceConfig(selectedPriceIds, (filteredFee) => {
      const editedDataTicket = getDataPostBooking().map((item: any) => {
        const priceId = item.price_id;
        if (filteredFee?.[priceId]) {
          return {
            ...item,
            ...filteredFee?.[priceId]
          };
        }
        return item;
      })

      // esp.log({
      //   order_type: EventConfigProperty?.state()?.get()?.order_type?.ticket,
      //   dataEvent: dataEvent,
      //   dataTicket: editedDataTicket.filter((x: any) => x.selected == 1),
      //   subscribed: subscribed,
      //   url_payment: urlPayment,
      //   show_fee_percentage
      // });

      LibNavigation.navigate('payment/ticket_multi', {
        order_type: EventConfigProperty?.state()?.get()?.order_type?.ticket,
        dataEvent: dataEvent,
        dataTicket: editedDataTicket?.filter((item: any) => item.selected == 1),
        subscribed: subscribed,
        url_payment: urlPayment,
        show_fee_percentage
      })
    })

  })

  function curlPriceConfig(price_ids: string[], onDone: (data: any) => void) {
    setLoading(true)
    if (getAvailableResult()?.url_price_config) {
      new LibCurl(getAvailableResult()?.url_price_config, null, (res, msg) => {
        setLoading(false)
        let filteredFee: any = {}
        if (res) {
          filteredFee = Object.fromEntries(
            price_ids.flatMap(k => res[k] ? [[k, res[k]]] : [])
          )
        }
        onDone(filteredFee)
      }, (err) => {
        setLoading(false)
        LibToastProperty.show(err?.message)
      })
    } else {
      setLoading(false)
      onDone({})
    }
  }

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

  function loadData() {
    new LibCurl(url, null, (res, msg) => {
      const availablePriceType = LibObject.update(res, (arr: any[]) => arr.filter((x) => x.status != 0))('price_type')
      const unAvailablePriceType = LibObject.update(res, (arr: any[]) => arr.filter((x) => x.status == 0))('price_type')

      setUnavailableResult(unAvailablePriceType)
      setAvailableResult(availablePriceType)
      setUrlPayment(res?.url_payment)
      setHasAdditionGlobal(res?.has_addition_global)

      // if (res.form_allotment == 1) {
      //   releaseQueue()
      //   LibNavigation.push('event/queue_out', { event_id: res.id, notes: res.form_allotment_text })
      // }

    }, (error) => {
      LibDialog.warningConfirm(esp.lang("event/ticket_list", "warn"), error?.message, "Ok", () => {
        LibNavigation.back()
      }, "", () => { })
    }, 1)
  }

  // function releaseQueue() {
  //   const { pathQueue, event_id, key } = EventQueue_pricingProperty.state().get()
  //   if (event_id && isInPricingQueueConfig(event_id)) {
  //     doneQueue(pathQueue, event_id, key, () => { })
  //     EventQueue_pricingProperty.state().reset()
  //     setIsPass(false)
  //     EventCountdownProperty.releaseQueue.trigger()
  //   }
  // }

  function onRefresh() {
    loadData()
  }



  function checkSeatMap() {
    let newResult: any[] = [];

    availableResult.price_type.map((priceType: any) => {
      let filteredList = priceType.list/* .filter((item: any) => item.selected == 1); */
      filteredList = filteredList?.map((item: any) => ({
        ...item,
        type: priceType?.type,
        tax: priceType?.tax,
        term: priceType?.term,
        has_addition: priceType?.has_addition,
        image_map: priceType?.image_map,
        use_seat: priceType?.use_seat,
        adjacent_seats: priceType?.config?.seat_autopick,
        fee_amount: priceType?.fee_amount,
        fee_type: priceType?.fee_type,
      }))

      newResult = newResult.concat(filteredList);
    });
    // if (getDataPostBooking().length == 0) {
    // }
    setDataPostBooking(newResult)
    resetTicketSeat()
    ticketSeat(newResult.filter((x: any) => x.selected == 1))
  }

  function selectSinglePrice(priceTypes: any, selectedItem: any) {
    return priceTypes.map((priceType: any) => {
      // reset parent
      let updated = {
        ...priceType,
        selected: 0,
        qty: 0,
        list: priceType.list.map((child: any) => ({
          ...child,
          selected: 0,
          qty: 0
        }))
      };

      // kalau cocok, aktifkan parent & child
      if (priceType.price_id === selectedItem.price_id) {
        updated.selected = 1;
        updated.qty = selectedItem.qty_min;

        updated.list = updated.list.map((child: any) => ({
          ...child,
          selected: 1,
          qty: selectedItem.qty_min
        }));
      }

      return updated;
    });
  }

  // contoh penggunaan:

  function renderItem(itemC: any, iC: number, item: any, i: number) {
    // itemC adalah item yang ada diindex list, kalo item itu adalah item yang ada diindex price_type

    let ticketWithDate = item.price_date == 1 && item.use_code == 0
    let ticketInvitation = item.price_date == 0 && item.use_code == 1
    let ticketSpecial = item.price_date == 0 && item.use_code == 0

    let _selectedTicket = itemC.selected == 1

    let colorDefault = _selectedTicket ? "#FFE9AD" : '#fff'
    let colorBackground = item.status != 1 ? LibStyle.colorLightGrey : itemC.status != 1 ? LibStyle.colorLightGrey : colorDefault
    let textOpacity = /* item.status == 1 ? 1 :  */itemC?.status == 1 ? 1 : 0.3

    let showCountDown = getAvailableResult()?.countdown_booking == "1" && itemC?.status == 1 && item?.status == 1 && item?.date_start != "0000-00-00 00:00:00" && item?.date_end != "0000-00-00 00:00:00" && moment(item?.date_end).format("YYYY-MM-DD HH:mm:ss") >= moment().format("YYYY-MM-DD HH:mm:ss")
    let dateShowed = item?.price_date == 1 ?
      moment(item?.date_end).format("YYYY-MM-DD HH:mm:ss") > moment(itemC?.ondate).format("YYYY-MM-DD HH:mm:ss") ? moment(itemC?.ondate).add(1, "days").format("YYYY-MM-DD HH:mm:ss") : item?.date_end
      : item?.date_end


    return (
      <TouchableOpacity key={iC} onPress={() => {
        let msg = ""
        if (item?.status == 1) {
          if (itemC?.status != 1) {
            msg = itemC?.status == 2 ? esp.lang("event/ticket_list", "coming_soon") : esp.lang("event/ticket_list", "sold_out")
          }
        } else {
          msg = item?.status == 2 ? esp.lang("event/ticket_list", "coming_soon") : esp.lang("event/ticket_list", "sold_out")
        }
        // let msg = item.status == 0 ? esp.lang("event/ticket_list", "sold_out") : esp.lang("event/ticket_list", "coming_soon")
        if (itemC.status == 1 && item.status == 1) {
          if (is_multiprice) {
            const data = new LibObject(getAvailableResult())
              .update((itemList) => {
                itemList.selected = itemList.selected == 1 ? 0 : 1
                itemList.qty = itemList.selected == 1 ? item.qty_min : 0
                itemList.adjacent_seats = item.config?.seat_autopick
                itemList.use_seat = item.use_seat
                return itemList
              })('price_type', i, 'list', iC)
              .update((priceTypeItem) => {
                return ({
                  ...priceTypeItem,
                  selected: priceTypeItem.list.some((item: any) => item.selected == 1) ? 1 : 0
                })
              })('price_type', i)
              .value()

            setAvailableResult(data)
          } else {
            const updatedData = selectSinglePrice(availableResult?.price_type, { price_id: item?.price_id, qty_min: item?.qty_min });
            const data = {
              ...getAvailableResult(),
              price_type: updatedData
            }

            setAvailableResult(data)
          }

        } else if (itemC.status == 0) {
          LibToastProperty.show(msg)
        } else if (itemC.status == 2) {
          LibToastProperty.show(msg)
        }

      }} testID="ticket_item" activeOpacity={itemC.status == 1 ? 0 : 1} style={{ backgroundColor: colorBackground, borderBottomWidth: item.list.length == 1 ? 0 : 5, borderBottomColor: "#fff" }}>
        <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', padding: 10, alignItems: 'center' }}>
          {
            ticketWithDate ?
              // view untuk yang ada tanggalnya
              <View style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center', }}>
                <View style={applyStyle({ marginLeft: 10, marginHorizontal: 20, width: 42, height: 42, borderRadius: 5, backgroundColor: colorBackground, borderStyle: "solid", borderWidth: textOpacity, borderColor: _selectedTicket ? "#3ea4dc" : '#999', alignContent: 'center', alignItems: 'center', justifyContent: 'center' })}>
                  <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0.23, textAlign: "center", color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC.ondate).localeFormat('DD')}</Text>
                </View>
                <View style={applyStyle({ flexDirection: 'column', flex: 1 })}>
                  {
                    item?.status == 1 && itemC.status != 1 &&
                    <View style={applyStyle({ flexDirection: 'row', marginBottom: 5 })}>
                      <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', marginTop: 5, borderWidth: 1, backgroundColor: itemC.status == 0 ? LibStyle.colorRed : "#4cd964", borderColor: itemC.status == 0 ? LibStyle.colorRed : "#4cd964", borderRadius: 5, padding: 3, opacity: 0.8 })}>
                        <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color: /* itemC.status == 2 ? "#000" : */ "#fff", fontWeight: 'bold' })}>{itemC.status == 0 ? esp.lang("event/ticket_list", "sold_out") : esp.lang("event/ticket_list", "coming_soon")}</Text>
                      </View>
                    </View>
                  }
                  {
                    showCountDown ?
                      <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC?.ondate).localeFormat('dddd, MMMM YYYY')}</Text>
                      :
                      <>
                        <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC.ondate).localeFormat('dddd')}</Text>
                        <View style={applyStyle({ flexDirection: 'row' })}>
                          <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC.ondate).localeFormat('MMMM')}</Text>
                          <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, marginLeft: 7, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC.ondate).localeFormat('YYYY')}</Text>
                        </View>
                      </>
                  }
                  {
                    showCountDown &&
                    <EventCountdown_event date={dateShowed} containerStyle={{ marginVertical: -5 }} />
                  }
                </View>
              </View>
              :
              // view untuk yang undangan dan khusus
              <View style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                <LibPicture source={esp.assets(ticketInvitation ? 'icons/invitation2.png' : 'icons/ic_special2.png')} style={{ height: 42, width: 42 }} />
                <View style={{ marginLeft: 14, flex: 1 }} >
                  {
                    item?.status == 1 && itemC.status != 1 &&
                    <View style={applyStyle({ flexDirection: 'row', marginBottom: 5 })}>
                      <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', marginTop: 5, borderWidth: 1, backgroundColor: itemC.status == 0 ? LibStyle.colorRed : LibStyle.colorPrimary, borderColor: itemC.status == 0 ? LibStyle.colorRed : LibStyle.colorPrimary, borderRadius: 5, padding: 3, opacity: 0.8 })}>
                        <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color: "#fff", fontWeight: 'bold' })}>{itemC.status == 0 ? esp.lang("event/ticket_list", "sold_out") : esp.lang("event/ticket_list", "coming_soon")}</Text>
                      </View>
                    </View>
                  }
                  {<Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' }}>{item.type}</Text>}
                  {
                    item.info != "" &&
                    <EventHtmltext allowFontScaling={false} style={{ flexWrap: 'wrap', fontFamily: "Arial", fontSize: 11, fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' }}>{item.info}</EventHtmltext>
                  }
                </View>
              </View>
          }

          <View style={applyStyle({ marginRight: 5, marginLeft: 5, flexDirection: 'column' })} >
            {
              (itemC.status == 1 || itemC.status == 0 || itemC.show_price == 1) &&
              <Text allowFontScaling={false} style={applyStyle({ opacity: ticketWithDate ? textOpacity : 1, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "right", color: _selectedTicket ? "#3ea4dc" : (itemC.price == 0 ? LibStyle.colorGreen : '#999') })} >{itemC.price == 0 ? esp.lang("event/ticket_list", "free") : LibUtils.money(itemC.price, itemC.currency)}</Text>
            }
            {
              (ticketWithDate || ticketSpecial) && itemC.selected == 1 &&
              <View style={applyStyle({ marginTop: 4, flexDirection: 'row', marginLeft: 8, alignContent: 'center', alignItems: 'center' })}>
                <Pressable hitSlop={{ top: 15, left: 15, right: 15, bottom: 15 }} testID='minus_btn' onPress={() => {

                  let qty = 1

                  if (Number(itemC.qty) - 1 <= 0) {
                    // set 0 & unselect tiket
                    qty = 0

                    const data = new LibObject(getAvailableResult())
                      .update((itemList) => {
                        itemList.selected = 0 // langsung unselect
                        itemList.qty = 0
                        itemList.adjacent_seats = item.config?.seat_autopick
                        itemList.use_seat = item.use_seat
                        return itemList
                      })('price_type', i, 'list', iC)
                      .update((priceTypeItem) => {
                        return ({
                          ...priceTypeItem,
                          selected: priceTypeItem.list.some((item: any) => item.selected == 1) ? 1 : 0
                        })
                      })('price_type', i)
                      .value()

                    setAvailableResult(data)

                  } else {
                    // patuhi qty_min
                    if (itemC.qty <= item.qty_min) {
                      qty = Number(item.qty_min)
                    } else {
                      qty = Number(itemC.qty) - 1
                    }

                    // set qty baru
                    setAvailableResult(LibObject.set(getAvailableResult(), qty)('price_type', i, 'list', iC, 'qty'))
                  }

                }}>
                  <View style={applyStyle({ padding: 1, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center', justifyContent: 'center' })}>
                    <LibIcon name="minus" color="#e74c3c" />
                  </View>
                </Pressable>
                <Text style={applyStyle({ fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b", marginLeft: 13, marginRight: 13 })}>{itemC?.qty}</Text>
                <Pressable hitSlop={{ top: 15, left: 15, right: 15, bottom: 15 }} testID='plus_btn' onPress={() => {
                  // add(itemP.quota, itemP.quota_used)
                  let qty = 1
                  if (itemC.qty != item.qty_max) {
                    if (qty != (Number(itemC.quota) - Number(itemC.quota_used))) {
                      qty = Number(itemC?.qty) + 1
                    }
                  } else {
                    qty = Number(item.qty_max)
                  }
                  setAvailableResult(LibObject.set(getAvailableResult(), qty)('price_type', i, 'list', iC, 'qty'))
                }}>
                  <View style={applyStyle({ padding: 1, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center', justifyContent: 'center' })}>
                    <LibIcon name="plus" color="#16a085" />
                  </View>
                </Pressable>
              </View>
            }
          </View>

          {
            ticketWithDate && itemC.schedule?.artist?.length > 0 &&
            <TouchableOpacity onPress={() => {
              if (item.status == 1 && itemC.status == 1) {
                let itemTicket = {
                  ...item
                }
                let replaceList = LibObject.set(itemTicket, itemC)('list')
                // ini jika dia gajadi beli dari halaman schedule.
                // setSelectedTicket(replaceList)
                // setQtyGlobal(itemT)
                // releaseQueue()
                // ini untuk dikirim ke halaman schedule
                let dataPost: any = {
                  event_id: availableResult?.id,
                  event_title: availableResult?.title,
                  charge_payment: availableResult?.charge_payment,
                  charge_payment_type: availableResult?.charge_payment_type,
                  images: availableResult?.images,
                  selected_ticket: replaceList,
                  qty: itemC.hasOwnProperty("qty") ? itemC?.qty : 1,
                }

                LibNavigation.navigate('event/schedule', {
                  schedule: itemC.schedule,
                  order_type: EventConfigProperty?.state()?.get()?.order_type?.ticket,
                  tax: item?.tax,
                  dataBookingEvent: dataPost,
                  is_multiprice: 1
                })
              }


            }} activeOpacity={itemC.status == 1 ? 0 : 1} style={applyStyle({ padding: 5, opacity: 1 })} hitSlop={{ top: 15, left: 15, right: 15, bottom: 15 }} >
              <LibIcon name="information-outline" size={18} color={"#434343"} style={{ opacity: textOpacity }} />
            </TouchableOpacity>
          }


        </View>
      </TouchableOpacity>
    )
  }

  let listLength = new Array(10).fill('')

  const maxDisplay = 3;

  const handleShowAll = (price_id: any) => {
    setShowAll((prevShowAll: any) => ({
      ...prevShowAll,
      [price_id]: !prevShowAll[price_id],
    }));
  };

  if (!availableResult) {
    return (
      <View style={{ flex: 1, backgroundColor: '#fff' }}>
        <EventHeader title={esp.lang("event/ticket_list", "buy_ticket")} subtitle={esp.lang("event/ticket_list", "choose_date")} />
        <LibSkeleton>
          {
            listLength.map((item: any, i: number) => {
              return (
                <View key={i}>
                  <View style={{ height: 30, width: '100%', backgroundColor: '#fff' }} />
                  <View style={{ padding: 10, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
                    <View style={{ flexDirection: 'row' }}>
                      <View style={{ backgroundColor: '#fff', height: 42, width: 42, borderRadius: 3, marginRight: 10 }} />
                      <View style={{ width: '60%' }}>
                        <View style={{ backgroundColor: '#fff', height: 20, width: '40%' }} />
                        <View style={{ backgroundColor: '#fff', marginTop: 7, height: 14, width: '70%' }} />
                      </View>
                    </View>
                    <View style={{ backgroundColor: '#fff', height: 20, width: '10%' }} />
                  </View>
                </View>
              )
            })
          }
        </LibSkeleton>
      </View>
    )
  }

  return (
    <EventQueue event_id={Number(availableResult?.id)} >
      <View style={{ flex: 1, backgroundColor: '#fff' }}>
        {/* <LibFocus onFocus={onRefresh} /> */}
        <EventHeader title={esp.lang("event/ticket_list", "buy_ticket")} subtitle={esp.lang("event/ticket_list", "choose_date")} />
        {/* {
              Object.values(pendingData).filter((item: any) => item?.order_type == "ticket").length > 0 &&
              <EventPending_trx
                onPress={() => {
                  LibNavigation.navigate('bigbang/loading_page_list', {
                    order_type: 'ticket'
                  })
                }}
                order_type="ticket"
                title={esp.lang("event/ticket_list", "pending", String(Object.values(pendingData).filter((item: any) => item?.order_type == "ticket").length))}
              />
            } */}

        <EventQueueProperty.QueueCountdown
          onExpired={() => {
            LibNavigation.back()
          }}
        />

        <ScrollView refreshControl={<RefreshControl refreshing={false} onRefresh={onRefresh} />}>
          <UseCondition if={is_multiprice == 1} >
            <EventAlert
              color={LibStyle.colorPrimary}
              msg={esp.lang("event/ticket_list2", "u_can_choose_multiple")}
              style={{ marginHorizontal: 15 }}
              useIcon
            />
          </UseCondition>
          {
            availableResult?.image_map != "" &&
            <TouchableOpacity onPress={() => {
              LibNavigation.navigate('lib/gallery', { image: availableResult?.image_map })
            }} style={{ marginBottom: 10, marginTop: 20 }}>
              <LibPicture source={{ uri: availableResult?.image_map }} style={applyStyle({ alignSelf: 'center', height: LibStyle.width * 0.5, width: LibStyle.width })} resizeMode="contain" />
            </TouchableOpacity>
          }
          <View style={{ flex: 1 }}>
            {
              availableResult?.price_type?.map?.((item: any, i: number) => {
                let textOpacity = item?.status == 1 ? 1 : 0.3
                let filterFullData = availableResult?.price_type?.filter((it: any) => it.status != 0)
                const displayedData = showAll[item.price_id] ? item?.list : item?.list.slice(0, maxDisplay);

                let ticketWithDate = item.price_date == 1 && item.use_code == 0

                return (
                  <Pressable onPress={() => {

                  }} key={i} style={{ overflow: 'hidden', margin: 15, marginBottom: 5, marginTop: 10, backgroundColor: '#fff', borderRadius: 10, ...LibStyle.elevation(2), borderWidth: 1, borderColor: item.selected == 1 ? LibStyle.colorBlue : LibStyle.colorBgGrey }}>
                    <View style={{ padding: 10, backgroundColor: '#f1f2f3', borderTopLeftRadius: 10, borderTopRightRadius: 10 }}>
                      {
                        item?.hasOwnProperty('label') && (item?.label != "" && item?.label != null) &&
                        <View style={applyStyle({ flexDirection: 'row' })}>
                          <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', borderWidth: 1, backgroundColor: item?.label_color, borderColor: item?.label_color, borderRadius: 3, padding: 2, paddingHorizontal: 5, opacity: 1 })}>
                            <Text allowFontScaling={false} style={{ fontSize: 10, fontStyle: "normal", letterSpacing: 0.5, color: EventOrder_itemProperty.textColor(item?.label_color), fontWeight: 'bold' }}>{item?.label}</Text>
                          </View>
                        </View>
                      }
                      <View style={{ alignContent: 'center', alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between', }}>
                        <View style={{ flex: 2 }}>
                          <EventHtmltext allowFontScaling={false} style={{ opacity: textOpacity, fontWeight: 'bold' }}>{item.type}
                            {
                              item.qty_min > 1 &&
                              <Text style={{ color: LibStyle.colorRed, fontSize: 10, fontWeight: 'normal' }}> {"(" + esp.lang("event/ticket_list", "min_order") + LibUtils.number(item.qty_min) + ")"}</Text>
                            }
                          </EventHtmltext>
                          {
                            availableResult?.countdown_booking == "1" && displayedData?.length == 1 && item?.status == 1 && item?.date_start != "0000-00-00 00:00:00" && item?.date_end != "0000-00-00 00:00:00" && moment(item?.date_end).format("YYYY-MM-DD HH:mm:ss") >= moment().format("YYYY-MM-DD HH:mm:ss") &&
                            <EventCountdown_event date={item?.date_end} containerStyle={{ marginVertical: -5 }} />
                          }

                          {
                            deeplinkParams?.type == 'event-voucher' && deeplinkParams?.price_id == item.price_id ?
                              <Text allowFontScaling={false} style={{ color: "coral", fontSize: 12, fontWeight: 'bold' }}>{esp.lang("event/ticket_list", "applied_code", deeplinkParams?.code)}</Text>
                              : null
                          }
                        </View>

                        {
                          item?.status != 1 &&
                          <View style={applyStyle({ flex: 1, justifyContent: 'flex-end', flexDirection: 'row' })}>
                            <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', borderWidth: 1, backgroundColor: item.status == 0 ? LibStyle.colorRed : "#4cd964", borderColor: item.status == 0 ? LibStyle.colorRed : "#4cd964", borderRadius: 5, padding: 3, opacity: 0.8 })}>
                              <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color: item.status == 2 ? "#000" : "#fff", fontWeight: 'bold' })}>{item.status == 0 ? esp.lang("event/ticket_list", "sold_out") : esp.lang("event/ticket_list", "coming_soon")}</Text>
                            </View>
                          </View>
                        }
                      </View>
                      {
                        item.info != "" && ticketWithDate &&
                        <View style={{ marginTop: 3, alignContent: 'center', alignItems: 'center', flexDirection: 'row', marginRight: 5 }}>
                          <Text allowFontScaling={false} style={{ fontSize: 12, color: LibStyle.colorBlue }}>{item.info}</Text>
                        </View>
                      }
                    </View>
                    {
                      displayedData?.map((itemC: any, iC: number) => renderItem(itemC, iC, item, i))
                    }

                    {
                      filterFullData[i].list?.length > 3 &&
                      <TouchableOpacity onPress={() => {
                        handleShowAll(item.price_id)
                      }} style={{ borderTopColor: LibStyle.colorGrey, borderTopWidth: 0.8, flex: 1, padding: 8, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
                        <Text allowFontScaling={false} style={{ marginRight: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorBlue }}>{showAll[item.price_id] ? esp.lang("event/ticket_list", "see_less") : esp.lang("event/ticket_list", "see_more")}</Text>
                        <LibIcon name={showAll[item.price_id] ? 'chevron-double-up' : 'chevron-double-down'} color={LibStyle.colorBlue} size={18} />
                      </TouchableOpacity>
                    }

                  </Pressable>
                )
              })
            }

            {/* ini view yang dibawah */}
            <View style={{ marginTop: 30 }}>
              {
                unAvailableResult?.price_type?.length > 0 &&
                <View style={{ margin: 15, marginTop: 0, marginBottom: 0, paddingBottom: 10, borderBottomWidth: 1, borderBottomColor: LibStyle.colorGrey }}>
                  <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 16 }}>{esp.lang("event/ticket_list", "ticket_not_available")}</Text>
                </View>
              }
              {
                unAvailableResult?.price_type?.map?.((item: any, i: number) => {
                  let textOpacity = item?.status == 1 ? 1 : 0.3
                  let ticketWithDate = item.price_date == 1 && item.use_code == 0
                  return (
                    <View key={i} style={{ overflow: 'hidden', margin: 15, marginBottom: 5, backgroundColor: '#fff', borderRadius: 10, ...LibStyle.elevation(2), borderWidth: 1, borderColor: item.selected == 1 ? LibStyle.colorBlue : LibStyle.colorBgGrey }}>
                      <View style={{ padding: 10, backgroundColor: '#f1f2f3', borderTopLeftRadius: 10, borderTopRightRadius: 10 }}>
                        <View style={{ alignContent: 'center', alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between', }}>
                          <Text allowFontScaling={false} style={{ opacity: textOpacity, fontWeight: 'bold' }}>{item.type}</Text>
                          {
                            item?.status != 1 &&
                            <View style={applyStyle({ flexDirection: 'row' })}>
                              <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', borderWidth: 1, backgroundColor: item.status == 0 ? LibStyle.colorRed : "#4cd964", borderColor: item.status == 0 ? LibStyle.colorRed : "#4cd964", borderRadius: 5, padding: 3, opacity: 0.8 })}>
                                <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color: item.status == 2 ? "#000" : "#fff", fontWeight: 'bold' })}>{item.status == 0 ? esp.lang("event/ticket_list", "sold_out") : esp.lang("event/ticket_list", "coming_soon")}</Text>
                              </View>
                            </View>
                          }
                        </View>
                        {
                          item.info != "" && ticketWithDate &&
                          <View style={{ marginTop: 3, alignContent: 'center', alignItems: 'center', flexDirection: 'row', marginRight: 5 }}>
                            <Text allowFontScaling={false} style={{ fontSize: 12, color: LibStyle.colorBlue }}>{item.info}</Text>
                          </View>
                        }
                      </View>
                      {
                        item.list.slice(0, 3).map((itemC: any, iC: number) => renderItem(itemC, iC, item, i))
                      }
                    </View>
                  )
                })
              }
            </View>
          </View>
        </ScrollView>
        <View style={applyStyle({ margin: 10, marginVertical: 5 })}>
          {
            availableResult?.price_type_info != "" &&
            <Text allowFontScaling={false} style={applyStyle({ marginBottom: 10, fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorBlue })} >{availableResult && availableResult?.hasOwnProperty("price_type_info") && availableResult?.price_type_info}</Text>
          }
          {
            loading ?
              <View style={{ minWidth: '100%', alignSelf: 'center' }}  >
                <View style={{ borderWidth: 1, borderColor: 'rgba(0, 0, 0, 0)', height: 40, borderRadius: 16, backgroundColor: "#e6e6e6", alignItems: 'center', justifyContent: 'center', paddingHorizontal: 9 }} >
                  <ActivityIndicator size={"small"} color={LibStyle.colorPrimary} />
                </View>
              </View>
              :
              <EventButton testID={"next_btn"} label={esp.lang("event/ticket_list", "next")} onPress={() => {
                if (availableResult?.price_type.some((item: any) => item.selected == 1)) {
                  checkSeatMap();
                } else {
                  LibToastProperty.show(esp.lang("event/ticket_list", "ticket_not_select"), 3000)
                  return
                }

              }} style={applyStyle({ backgroundColor: LibStyle.colorPrimary })} />
          }
        </View>
      </View>
    </EventQueue>
  )
}