// withHooks
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 moment from 'esoftplay/moment';

import { applyStyle } from 'esoftplay';
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 { EventLayout } from 'esoftplay/cache/event/layout/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 { LibFocus } from 'esoftplay/cache/lib/focus/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/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 React, { useEffect, useRef } from 'react';
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventTicket_listArgs {

}
export interface EventTicket_listProps {

}

export 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,
  "passes"?: any
}

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

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

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

  const [unAvailableResult, setUnavailableResult] = useLazyState<any>()
  const [availableResult, setAvailableResult, getAvailableResult] = useSafeState<Result>()
  const [urlPayment, setUrlPayment] = useLazyState<any>()

  const [qty, setQty, getQty] = useSafeState<number>(1)
  const [selectedTicket, setSelectedTicket, getSelectedTicket] = useSafeState<any>()

  const [showAll, setShowAll] = useSafeState<any>({});

  const [loading, setLoading] = useSafeState<boolean>(false)

  const [tab, setTab] = useSafeState(0)
  const tabs = [
    { id: 1, title: "Pricing" },
    { id: 2, title: "Seat Layout" }
  ]

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

  function onRefresh() {
    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)

      if (selectedTicket) {
        res?.price_type?.map((item: any) => {
          if (item.price_id == selectedTicket?.price_id && item.status != 1) {
            setSelectedTicket(undefined)
          }
        })
      }

      // 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 add(quota?: any, quota_used?: any): void {
    if (getQty() != parseInt(getSelectedTicket()?.qty_max)) {
      if (getQty() != (parseInt(quota) - parseInt(quota_used))) {
        setQty(getQty() + 1)
      }
    }
  }

  function min(): void {
    const currentQty = getQty()
    const selectedTicket = getSelectedTicket()

    // kalau qty - 1 <= 0 → set qty 0 dan unselect tiket
    if (currentQty - 1 <= 0) {
      setQty(0)
      setSelectedTicket(null) // atau undefined sesuai project
      return
    }

    // ambil qty_min dengan cara manual
    let qtyMin = 1 // default
    if (selectedTicket && selectedTicket.qty_min) {
      qtyMin = Number(selectedTicket.qty_min)
    }

    // kurangi qty tapi tetap patuhi qty_min
    if (currentQty <= qtyMin) {
      setQty(qtyMin)
    } else {
      setQty(currentQty - 1)
    }
  }


  function setQtyGlobal(value: any) {
    let qty = 1
    if (getSelectedTicket()?.qty_min) {
      qty = Number(getSelectedTicket()?.qty_min)
    }
    if (qty > getSelectedTicket()?.qty_max) {
      qty = Number(getSelectedTicket().qty_max)
    }
    if (value.quota != 0 && qty > value.quota) {
      qty = value.quota
    }
    if (qty < 1) {
      qty = 1
    }
    setQty(qty)
  }

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

  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: selectedTicket,
    qty: getQty(),
  }

  async function checkAddition(newDataPost: any) {
    if ((selectedTicket?.hasOwnProperty("has_addition") && selectedTicket?.has_addition == 1)) {
      const additions = await LibNavigation.navigateForResult('event/additional', { type_ticket: selectedTicket?.type, ondate: selectedTicket?.list?.ondate, event_id: availableResult?.id, qty: getQty(), price_id: selectedTicket?.price_id }, 321)
      if (additions != "") {
        newDataPost.addition = additions
      }
    }
    curlPriceConfig(getSelectedTicket()?.price_id, (config) => {
      LibNavigation.navigate('payment/ticket', {
        order_type: eventConfig?.order_type?.ticket,
        tax: config?.tax || selectedTicket?.tax || 0,
        fee_platform: config.hasOwnProperty('fee_platform_amount') ? {
          fee_platform_amount: config?.fee_platform_amount || 0,
          fee_platform_type: config?.fee_platform_type || "NONE"
        } : fee_platform,
        fee_custom: {
          fee_custom_label: config?.fee_custom_label || "Custom Fee",
          fee_custom_amount: config?.fee_custom_amount || 0,
          fee_custom_type: config?.fee_custom_type || "NONE"
        },
        dataBookingEvent: { ...newDataPost, qty: getQty() },
        subscribed: subscribed,
        url_payment: urlPayment,
        show_fee_percentage
      })
    })
  }

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

  function nextStep(onALine?: number) {
    // releaseQueue()
    if (selectedTicket?.config?.seat_autopick == 1 && getQty() > 1) {
      dataPost.adjacent_seats = 1
    }

    if (selectedTicket?.use_code == 1 && selectedTicket?.use_seat == 1) {
      // tak arahke halaman seng anyar
      LibNavigation.navigate('payment/event_invitation', {
        dataBookingEvent: dataPost,
        subscribed: subscribed,
        show_fee_percentage
      })
    } else if (selectedTicket?.use_seat == 1) {
      if (selectedTicket?.config && selectedTicket?.config?.seat_autopick == 1) {
        checkAddition(dataPost)
      } else {
        LibNavigation.navigateForResult('event/seat_map_new', {
          url: 'event_seat',
          dataTicket: dataPost,
        }).then((value) => {
          dataPost.seat_label = value.seat_label
          checkAddition(dataPost)
        })
      }
    } else {
      checkAddition(dataPost)
    }
  }

  function checkInvBlock() {
    LibProgress.show(esp.lang("event/ticket_list", "wait"))
    new LibCurl('voucher_check_validate', null, (res, msg) => {
      LibProgress.hide()
      if (res?.status == 1) {
        LibNavigation.navigate('event/block_invitation', {
          dataCheck: res,
        })
      } else {
        nextStep()
      }
    }, (err) => {
      LibProgress.hide()
    })
  }

  function renderItem(item: any, itemT: any, iT: number) {
    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 = item.price_id == selectedTicket?.price_id && itemT.date_id == selectedTicket?.list?.date_id

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

    let showCountDown = getAvailableResult()?.countdown_booking == "1" && itemT?.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(itemT?.ondate).format("YYYY-MM-DD HH:mm:ss") ? moment(itemT?.ondate).add(1, "days").format("YYYY-MM-DD HH:mm:ss") : item?.date_end
      : item?.date_end

    return (
      <TouchableOpacity key={iT} onPress={() => {
        let itemTicket = {
          ...item
        }
        let replaceList = LibObject.set(itemTicket, itemT)('list')
        // kondisi untuk tipe tiket yang ada tanggalnya
        let msg = itemT.status == 0 ? esp.lang("event/ticket_list", "sold_out") : esp.lang("event/ticket_list", "coming_soon")
        if (ticketWithDate) {
          if (item.status == 1 && itemT.status == 1) {
            setSelectedTicket(replaceList)
            setQtyGlobal(itemT)
          } else if (item.status == 0) {
            LibToastProperty.show(msg)
          } else if (item.status == 2) {
            LibToastProperty.show(msg)
          }
        } else {
          // kondisi untuk tipe tiket yang tidak ada tanggalnya (undangan/khusus)
          if (item.status == 1 && itemT.status == 1) {
            setSelectedTicket(replaceList)
            if (ticketInvitation) {
              setQty(1)
            } else {
              setQtyGlobal(itemT)
            }
          } else if (item.status == 0) {
            LibToastProperty.show(msg)
          } else if (item.status == 2) {
            LibToastProperty.show(msg)
          }
        }
      }} testID="ticket_item" activeOpacity={itemT.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(itemT.ondate).localeFormat('DD')}</Text>
                </View>
                <View style={applyStyle({ flexDirection: 'column', flex: 1 })}>
                  {
                    item?.status == 1 && itemT.status != 1 &&
                    <View style={applyStyle({ flexDirection: 'row', marginBottom: 5 })}>
                      <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', marginTop: 5, borderWidth: 1, backgroundColor: itemT.status == 0 ? LibStyle.colorRed : "#4cd964", borderColor: itemT.status == 0 ? LibStyle.colorRed : "#4cd964", borderRadius: 5, padding: 3, opacity: 0.8 })}>
                        <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color: /* itemT.status == 2 ? "#000" : */ "#fff", fontWeight: 'bold' })}>{itemT.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(itemT.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(itemT.ondate).localeFormat('dddd')}</Text>
                        <View style={applyStyle({ flexDirection: 'row', alignItems: "center" })}>
                          <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemT.ondate).localeFormat('MMMM')}</Text>
                          <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, marginLeft: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemT.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 && itemT.status != 1 &&
                    <View style={applyStyle({ flexDirection: 'row', marginBottom: 5 })}>
                      <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', marginTop: 5, borderWidth: 1, backgroundColor: itemT.status == 0 ? LibStyle.colorRed : LibStyle.colorPrimary, borderColor: itemT.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' })}>{itemT.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' })} >
            {
              (itemT.status == 1 || itemT.status == 0 || itemT.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" : (itemT.price == 0 ? LibStyle.colorGreen : '#999') })} >{itemT.price == 0 ? esp.lang("event/ticket_list", "free") : LibUtils.money(itemT.price, itemT.currency)}</Text>
            }
            {/* {
              item.status == 1 && itemT.show_limit == 1 &&
              <Text allowFontScaling={false} style={{ textAlign: "right", marginBottom: 5, fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 1, color: LibStyle.colorRed }}> {quotaDifference <= 0 ? "Habis" : quotaDifference > 0 ? "Tersisa " + LibUtils.number(quotaDifference) : "Habis"}</Text>
            } */}

            {
              (ticketWithDate || ticketSpecial) && item.price_id == selectedTicket?.price_id && itemT.date_id == selectedTicket?.list?.date_id &&
              <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={() => { min() }}>
                  <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 })}>{qty}</Text>
                {/* </TouchableOpacity> */}
                <Pressable hitSlop={{ top: 15, left: 15, right: 15, bottom: 15 }} testID='plus_btn' onPress={() => {
                  add(itemT.quota, itemT.quota_used)
                }}>
                  <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 && itemT.schedule?.artist?.length > 0 &&
            <TouchableOpacity onPress={() => {
              if (item.status == 1 && itemT.status == 1) {
                let itemTicket = {
                  ...item
                }
                let replaceList = LibObject.set(itemTicket, itemT)('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: getQty(),
                }

                LibNavigation.navigate('event/schedule', {
                  schedule: itemT.schedule,
                  order_type: eventConfig?.order_type?.ticket,
                  tax: selectedTicket?.tax == null ? 0 : selectedTicket?.tax,
                  dataBookingEvent: dataPost,
                  is_multiprice: 0
                })
              }


            }} activeOpacity={itemT.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()
              }}
            />

            {
              esp.isDebug("") && availableResult?.price_type.some((x) => x.use_seat == "1") &&
              <View style={{ height: 43, marginBottom: 2, flexDirection: 'row', backgroundColor: '#fff', borderBottomWidth: 1, borderBottomColor: '#f2f2f2' }} >
                {
                  tabs.map((item: any, i: number) => (
                    <Pressable key={i} onPress={() => {
                      setTab(i)
                    }}>
                      <View style={{ height: 43, width: LibStyle.width / tabs.length, alignItems: 'center', overflow: 'visible', justifyContent: 'center', backgroundColor: '#fff' }}>
                        <Text style={{
                          width: LibStyle.width / tabs.length, fontSize: tab == i ? 13 : 12,
                          fontWeight: tab == i ? "bold" : "normal",
                          fontStyle: "normal", letterSpacing: 0, textAlign: "center",
                          color: tab == i ? LibStyle.colorPrimary : "#c5c5c5"
                        }}>{item.title}</Text>
                        <View style={{ marginTop: 2, width: 5, height: 5, borderRadius: 2.5, alignItems: 'center', justifyContent: 'center', backgroundColor: LibStyle.colorRed, opacity: item.total > 0 ? 1 : 0 }} />
                        <View style={{ width: (LibStyle.width / tabs.length) - 20, height: 3, backgroundColor: tab == i ? LibStyle.colorPrimary : "#fff", position: 'absolute', bottom: 0 }} />
                      </View>
                    </Pressable>
                  ))
                }
              </View>
            }
            {
              tab == 0 ?
                <>
                  <ScrollView refreshControl={<RefreshControl refreshing={false} onRefresh={onRefresh} />}>
                    {
                      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 selTic = item.price_id == selectedTicket?.price_id
                          let ticketWithDate = item.price_date == 1 && item.use_code == 0

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

                            }} key={i} style={{ overflow: 'hidden', margin: 15, marginBottom: 5, backgroundColor: '#fff', borderRadius: 5, borderWidth: 1.5, borderColor: selTic ? LibStyle.colorBlue : LibStyle.colorBgGrey }}>
                              <View style={{ padding: 10, backgroundColor: '#f1f2f3', borderTopLeftRadius: 5, borderTopRightRadius: 5 }}>
                                {
                                  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((itemT: any, iT: number) => renderItem(item, itemT, iT))
                              }

                              {
                                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-up-circle-outline' : 'chevron-down-circle-outline'} 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 selTic = item.price_id == selectedTicket?.price_id
                            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: selTic ? 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', }}>
                                    <View style={{ flex: 3 }}>
                                      <EventHtmltext allowFontScaling={false} style={{ opacity: textOpacity, fontWeight: 'bold' }}>{item.type}</EventHtmltext>
                                    </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>
                                {
                                  item?.list?.map((itemT: any, iT: number) => renderItem(item, itemT, iT))
                                }
                              </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: 10, 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 (!selectedTicket) {
                            LibToastProperty.show(esp.lang("event/ticket_list", "ticket_not_select"), 3000)
                            return
                          }
                          if (selectedTicket?.use_code == 1) {
                            checkInvBlock()
                          }
                          // else if (selectedTicket?.config?.seat_autopick == 1 && getQty() > 1) {
                          //   chooseBestSeat()
                          // }
                          else {
                            nextStep();
                          }

                        }} style={applyStyle({ backgroundColor: selectedTicket ? LibStyle.colorPrimary : "#f1f2f3" })} />
                    }
                  </View>

                </>
                :
                <EventLayout
                  is_multiprice={is_multiprice == 1 ? true : false}
                  result={availableResult}
                  priceTypes={[...availableResult.price_type, ...unAvailableResult?.price_type]}
                />
            }
          </>
        }

      </View>
    </EventQueue>
  )
}