// withHooks
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { useEffect } from 'react';

import { applyStyle } from 'esoftplay';
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventCheckout } from 'esoftplay/cache/event/checkout/import';
import { EventHtmltext } from 'esoftplay/cache/event/htmltext/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibList } from 'esoftplay/cache/lib/list/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/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 { ActivityIndicator, Pressable, Text, View } from 'react-native';


export interface EventOrder_detail_upgradeArgs {

}
export interface EventOrder_detail_upgradeProps {

}
export default function m(props: EventOrder_detail_upgradeProps): any {
  const { dataTicket, url }: any = esp.mod("lib/navigation").getArgsAll(props)
  const [selectedTicket, setSelectedTicket, getSelectedTicket] = useSafeState()
  const [result, setResult, getResult] = useSafeState()
  const [error, setError] = useSafeState()
  const [loading, setLoading] = useSafeState(false)
  // const [resultEvent, setResultEvent] = useSafeState()

  function loadDataUpgradeTicket() {
    new LibCurl(url, null, (res: any, msg: string) => {
      // setAvailableUpgrade(res?.list)
      setResult(res)
    }, (err: any) => {
      setError(err)
    })
  }

  // function loadDataEvent() {
  //   new LibCurl("event_detail/" + dataTicket?.event_id, null, (res: any, msg: string) => {
  //     setResultEvent(res)
  //   }, (err: any) => {

  //   })
  // }


  useEffect(() => {
    loadDataUpgradeTicket()
    // loadDataEvent()
  }, [])

  function renderItem(item: any, i: number) {
    let textOpacity = item?.status == 1 ? 1 : 0.3
    let ticketWithDate = item.price_date == 1 && item.use_code == 0
    let selTic = selectedTicket?.selected_ticket?.id == item.id
    return (
      <Pressable onPress={() => {
        if (item.status == 1) {
          let a = {
            event_id: dataTicket?.event_id,
            selected_ticket: {
              ...item,
              price_to: item?.is_remainer == 0 ? (Number(item?.amount_difference) / Number(dataTicket?.qty_upgrade)) : item?.price_to, //kondisi jika upgrade fixprice
              price_id: item.price_id_to,
              list: {
                ondate: item.ondate
              },
            },
            qty: dataTicket?.qty_upgrade,
            // tax_event: item.tax
          }
          setSelectedTicket(a)
        }
      }} key={i} style={{

        margin: 15, marginTop: 0, borderRadius: 5, overflow: 'hidden', borderWidth: 1.5, borderColor: selTic ? LibStyle.colorBlue : LibStyle.colorBgGrey
      }}>
        <View style={{ padding: 10, backgroundColor: '#f1f2f3', borderTopLeftRadius: 5, borderTopRightRadius: 5 }}>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
            <View style={{ flex: 3 }}>
              <EventHtmltext allowFontScaling={false} style={{ opacity: textOpacity, fontWeight: 'bold', color: item.status != 1 ? "#c9c9c9" : selTic ? LibStyle.colorBlue : "#000" }}>{item.price_name_to} </EventHtmltext>
            </View>
            {
              item?.status != 1 &&
              <View style={applyStyle({ alignSelf: 'center', flexDirection: 'row' })}>
                <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', borderWidth: 1, backgroundColor: (item.status == 0 || item?.status == 3) ? LibStyle.colorRed : "#4cd964", borderColor: (item.status == 0 || item?.status == 3) ? LibStyle.colorRed : "#4cd964", borderRadius: 5, padding: 3, opacity: 0.8 })}>
                  <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color: "#fff", fontWeight: 'bold' })}>{item?.status_text}</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>
        <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', padding: 10, alignItems: 'center' }}>
          <View style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
            <LibPicture source={esp.assets('icons/ic_special2.png')} style={{ height: 42, width: 42 }} />
            <View style={{ marginLeft: 14, flex: 1 }} >
              {
                item.info != "" &&
                <EventHtmltext allowFontScaling={false} style={{ flexWrap: 'wrap', fontFamily: "Arial", fontSize: 11, fontStyle: "normal", letterSpacing: 0, color: '#999' }}>{item.info}</EventHtmltext>
              }
            </View>
            <Text allowFontScaling={false} style={{ textAlign: 'center', fontSize: 14, fontWeight: 'bold', marginTop: 5, color: item.status != 1 ? "#c9c9c9" : selTic ? LibStyle.colorBlue : "#000" }}>{"+ "}{item?.is_remainer == "0" ? LibUtils.money(item?.price_difference, item?.currency) : LibUtils.money(item?.amount_difference, item?.currency)}</Text>

          </View>
        </View>
      </Pressable>
    )
  }

  if (!result && !error) {
    const LibLoading = esp.mod("lib/loading")
    return <LibLoading />
  }

  if (error) {
    return (
      <View style={{ flex: 1 }} >
        <EventHeader title={esp.lang("event/order_detail_upgrade", "header_title")} subtitle={dataTicket?.event_name} />
        <View style={{ flex: 1 }}>
          <EventMessage message={error?.message} children={
            <EventButton
              label='Kembali'
              style={{ margin: 15, marginHorizontal: 30 }}
              onPress={() => LibNavigation.back()}
            />
          } />
        </View>
      </View>
    )
  }

  const sorted = result?.list?.sort((a: any, b: any) => {
    // jika a.status = 1 dan b bukan 1 → a di atas
    if (a.status == 1 && b.status != 1) return -1;
    // jika b.status = 1 dan a bukan 1 → b di atas
    if (b.status == 1 && a.status != 1) return 1;
    // jika dua-duanya sama statusnya → urutan tidak berubah
    return 0;
  });

  return (
    <View style={{ flex: 1 }} >
      <EventHeader title={esp.lang("event/order_detail_upgrade", "header_title")} subtitle={dataTicket?.event_name} />
      <View style={{ flex: 1 }}>
        <LibTextstyle textStyle='m_overline' text={esp.lang("event/order_detail_upgrade", "current_ticket")} style={{ fontSize: 12, margin: 15, marginBottom: 0 }} />

        <View style={{ ...LibStyle.elevation(2), margin: 15, width: LibStyle.width - 30, borderRadius: 10, backgroundColor: LibStyle.colorBgGrey, padding: 10, height: 100, alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
          <EventHtmltext allowFontScaling={false} style={{ marginHorizontal: 5, fontSize: 20, color: "#000", textAlign: 'center', fontWeight: 'bold' }} numberOfLines={2} ellipsizeMode={'tail'}>{result?.price_name_from || dataTicket?.price_name}</EventHtmltext>
          <Text allowFontScaling={false} style={{ color: "#000", marginTop: 10 }}>{LibUtils.money(result?.total_from, result?.currency || dataTicket?.currency)}</Text>

          <View style={applyStyle({ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 })}>
            <View style={applyStyle({ width: 25, height: 25, borderRadius: 12.5, backgroundColor: "#fff", marginLeft: -12.5 })} />
            <View style={applyStyle({ flex: 1 })} />
            <View style={applyStyle({ width: 25, height: 25, borderRadius: 12.5, backgroundColor: "#fff", marginRight: -12.5 })} />
          </View>
        </View>

        <LibTextstyle textStyle='m_overline' text={esp.lang("event/order_detail_upgrade", "upgrade_to")} style={{ fontSize: 12, margin: 15, marginBottom: 10 }} />

        <LibList
          data={sorted}
          extraData={selectedTicket}
          renderItem={renderItem}
        />

      </View>
      <View style={{ padding: 10 }}>
        {
          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 label={esp.lang("event/order_detail_upgrade", "btn_next")} onPress={async () => {
              const selectedTicket = getSelectedTicket()

              if (!selectedTicket) {
                LibToastProperty.show(esp.lang("event/order_detail_upgrade", "select_ticket"))
                return
              }

              let seatData: any = {}
              if (selectedTicket?.selected_ticket?.use_seat == 1) {
                if (selectedTicket?.selected_ticket?.seat_autopick != 1) {
                  const seat = await LibNavigation.navigateForResult('event/seat_map_new', {
                    url: 'event_seat',
                    dataTicket: selectedTicket
                  })
                  seatData = {
                    ...seatData,
                    seat_label: seat?.seat_label
                  }
                }
              }

              setLoading(true)
              const config = await EventCheckout().curlPriceConfig(getResult()?.url_price_config, selectedTicket?.selected_ticket?.price_id_to)
              setLoading(false)

              const args = {
                dataTicket: {
                  url_payment: result?.url_payment,
                  url_upgrade: result?.url_upgrade,
                  price_name: result?.price_name_from || dataTicket?.price_name,
                  previous_total: selectedTicket?.selected_ticket?.is_remainer == 0 ? 0 : Number(result?.total_from),//kondisi jika upgrade fixprice
                  booking_id: dataTicket?.id,
                  qty_upgrade: dataTicket?.qty_upgrade,
                  tax_event: config?.tax,
                  ondate: dataTicket?.ondate,
                  event_title: dataTicket?.event_name,
                  event_id: dataTicket?.event_id,
                },
                selectedTicket: {
                  ...selectedTicket,
                  ...seatData
                },
                fee_platform: {
                  fee_platform_amount: config?.fee_platform_amount,
                  fee_platform_type: config?.fee_platform_type,
                },
                fee_custom: {
                  fee_custom_label: config?.fee_custom_label,
                  fee_custom_amount: config?.fee_custom_amount,
                  fee_custom_type: config?.fee_custom_type,
                }
              }

              LibNavigation.navigate('event/order_detail_upgrade_payment', args)

            }}
              backgroundColor={selectedTicket ? LibStyle.colorGreen : LibStyle.colorGrey}
              fontColor='#fff'
            />
        }
      </View>
    </View>
  )
}