// withHooks
// noPage

import { applyStyle } from 'esoftplay';
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventOrder_itemProperty } from 'esoftplay/cache/event/order_item/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/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 esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventTicketArgs {

}
export interface EventTicketProps {
  title?: string,
  priceList: any[],
  multiprice?: boolean,
  onSelectTickets: (data: any[]) => void
}

export default function m(props: EventTicketProps): any {
  const { title } = props
  const is_multiprice = props?.multiprice || false
  const [priceData, setPriceData, getPriceData] = useSafeState<any>(props?.priceList)
  const [showAll, setShowAll] = useSafeState<any>({});

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

  function handleSelect() {
    let newResult: any[] = [];
    getPriceData().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,
        list_id: priceType?.price_id + "-" + item.ondate,
        price_id: priceType?.price_id,
        use_code: priceType?.use_code,
        config: { ...priceType?.config },
        list: {
          ...item
        },
      }))
      newResult = newResult.concat(filteredList);
    })
    props.onSelectTickets(newResult)
  }

  function sortByStatus(data: any) {
    // Fungsi sorting untuk memastikan status 1 di atas, lainnya di bawah
    const statusSorter = (a: any, b: any) => {
      if (a.status == 1 && b.status != 1) return -1; // a = 1, b bukan 1 -> a di atas
      if (a.status != 1 && b.status == 1) return 1;  // a bukan 1, b = 1 -> b di atas
      return a.status - b.status; // Urutkan status selain 1 secara alami
    };

    return data
      .map((item: any) => {
        // Sorting array 'list' di dalam setiap item
        const sortedList = item?.list?.sort(statusSorter);
        return { ...item, list: sortedList };
      })
      .sort(statusSorter); // Sorting array utama
  }


  function renderItem(itemC: any, iC: number, item: any, i: number) {
    let ticketWithDate = item.price_date == 1 && item.use_code == 0
    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 = itemC?.status == 1 ? 1 : 0.3

    return (
      <TouchableOpacity
        onPress={() => {
          let msg = itemC?.status == 0 ? esp.lang("event/artist_detail", "sold_out") : esp.lang("event/artist_detail", "coming_soon")

          // kondisi untuk tipe tiket yang ada tanggalnya
          if (item?.status == 1 && itemC?.status == 1) {
            let data: any = []
            if (is_multiprice) {
              data = new LibObject(getPriceData())
                .update((itemList) => {
                  itemList.selected = itemList.selected == 1 ? 0 : 1
                  itemList.qty = itemList.selected == 1 ? item.qty_min : 0
                  itemList.seat_autopick = item.config?.seat_autopick
                  itemList.use_seat = item.use_seat
                  return itemList
                })(i, 'list', iC)
                .update((priceTypeItem) => {
                  return ({
                    ...priceTypeItem,
                    selected: priceTypeItem.list.some((item: any) => item.selected == 1) ? 1 : 0
                  })
                })(i)
                .value()
            } else {
              data = new LibObject(getPriceData())
                .update((itemList) => itemList.map((x: any) => {
                  return {
                    ...x,
                    selected: (x.list_id == itemC.list_id && x.price_id == item.price_id) ? 1 : 0,
                    qty: (x.list_id == itemC.list_id && x.price_id == item.price_id) ? (item.qty_min | 1) : 0,
                    seat_autopick: item.config?.seat_autopick,
                    use_seat: item.use_seat
                  }
                }))(i, 'list')
                .update((priceTypeItem) => priceTypeItem.map((x: any) => {
                  return {
                    ...x,
                    list: x.price_id != item.price_id ? x.list.map((t: any) => ({ ...t, selected: 0 })) : x.list,
                    selected: x.price_id == item.price_id ? 1 : 0
                  }
                })
                )()
                .value()
            }
            setPriceData(data)
          } else if (itemC?.status == 0) {
            LibToastProperty.show(msg)
          } else if (itemC?.status == 2) {
            LibToastProperty.show(msg)
          }
        }} activeOpacity={itemC?.status == 1 ? 0 : 1} key={iC} style={{ borderBottomWidth: item.list.length == 1 ? 0 : 5, borderBottomColor: "#fff", flex: 1, flexDirection: 'row', backgroundColor: colorBackground, justifyContent: 'space-between', padding: 10, alignItems: 'center' }}>
        {
          itemC.ondate == "0000-00-00" ?
            <LibPicture source={esp.assets('icons/ic_special2.png')} style={{ height: 42, width: 42 }} />
            :
            <>
              <View style={applyStyle({ marginLeft: 10, marginHorizontal: 20, width: 42, height: 42, borderRadius: 5, backgroundColor: "#fff", borderStyle: "solid", borderWidth: 1, 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/artist_detail", "sold_out") : esp.lang("event/artist_detail", "coming_soon")}</Text>
                    </View>
                  </View>
                }
                <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>
              </View>
            </>
        }

        <View style={applyStyle({ marginRight: 5, marginLeft: 5, flexDirection: 'column' })} >
          {
            (itemC?.status == 1 || itemC?.status == 0) &&
            <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, item.currency)}</Text>
          }
          {
            item?.status == 1 && (ticketWithDate || ticketSpecial) && itemC.selected == 1 &&
            <View style={applyStyle({ marginTop: 4, flexDirection: 'row', marginLeft: 8, alignContent: 'center', alignItems: 'center' })}>
              <TouchableOpacity onPress={() => {
                let qty = 1
                if (Number(itemC.qty) - 1 <= 0) {
                  // set 0 & unselect tiket
                  qty = 0

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

                  setPriceData(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
                  setPriceData(LibObject.set(getPriceData(), qty)(i, 'list', iC, 'qty'))
                }

              }}>
                <View style={applyStyle({ width: 28, height: 28, borderRadius: 6, backgroundColor: "#ecf0f1", justifyContent: 'center', alignContent: 'center', alignItems: 'center' })}>
                  <LibIcon name="minus" color="#e74c3c" />
                </View>
              </TouchableOpacity>
              <Text style={applyStyle({ fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b", marginLeft: 13, marginRight: 13 })}>{itemC?.qty}</Text>
              <TouchableOpacity onPress={() => {
                // add()
                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)
                }

                setPriceData(LibObject.set(getPriceData(), qty)(i, 'list', iC, 'qty'))
              }}>
                <View style={applyStyle({ width: 28, height: 28, borderRadius: 6, backgroundColor: "#ecf0f1", justifyContent: 'center', alignContent: 'center', alignItems: 'center' })}>
                  <LibIcon name="plus" color="#16a085" />
                </View>
              </TouchableOpacity>
            </View>
          }
        </View>
      </TouchableOpacity>
    )
  }

  return (
    <>
      {
        title && title != "" &&
        <Text allowFontScaling={false} style={applyStyle({ marginBottom: 15, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, textAlign: "center", color: "#34495e" })}>{title || esp.lang("event/artist_detail", "select_date")}</Text>
      }
      <ScrollView showsVerticalScrollIndicator={false} >
        {
          priceData?.length > 0 && sortByStatus(priceData)?.map((item: any, i: number) => {
            let filterFullData = priceData?.filter((it: any) => it.status != 0)
            const displayedData = showAll[item.price_id] ? item?.list : item?.list.slice(0, maxDisplay);

            let textOpacity = item?.status == 1 ? 1 : 0.3
            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 }}>
                  {
                    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', }}>
                    <Text allowFontScaling={false} style={{ opacity: textOpacity, fontWeight: 'bold' }}>{item.type}</Text>
                    {
                      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>
                    }
                    {
                      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/artist_detail", "sold_out") : esp.lang("event/artist_detail", "coming_soon")}</Text>
                        </View>
                      </View>
                    }
                  </View>
                  {
                    item.info != "" &&
                    <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-up-circle-outline' : 'chevron-down-circle-outline'} color={LibStyle.colorBlue} size={18} />
                  </TouchableOpacity>
                }

              </View>
            )
          })
        }
      </ScrollView>
      <View style={applyStyle({ flexDirection: 'row', paddingVertical: 10 })} >
        <EventButton label={is_multiprice ? "Pilih Tiket" : "Lanjutkan"} onPress={() => {
          if (getPriceData().some((t: any) => t?.selected == 1)) {
            handleSelect()
          } else {
            LibToastProperty.show(esp.lang("event/artist_detail", "select_tiket_first"))
          }
        }} style={{ backgroundColor: priceData?.some?.((t: any) => t?.selected == 1) ? LibStyle.colorGreen : "#eee", marginTop: 2, marginHorizontal: 15 }} />
      </View>
    </>
  )
}