// withHooks
import { useMemo, useRef } from 'react';

import { BigbangPayment_detail_ticket, BigbangPayment_detail_ticketProperty } from 'esoftplay/cache/bigbang/payment_detail_ticket/import';
import { BigbangPayment_list, BigbangPayment_listProperty } from "esoftplay/cache/bigbang/payment_list/import";
import { EventButton } from "esoftplay/cache/event/button/import";
import { EventHeader } from "esoftplay/cache/event/header/import";
import { EventTransaction } from 'esoftplay/cache/event/transaction/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 { LibProgress } from "esoftplay/cache/lib/progress/import";
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStyle } from "esoftplay/cache/lib/style/import";
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { PaymentFee_calculate } from 'esoftplay/cache/payment/fee_calculate/import';
import esp from "esoftplay/esp";
import useSafeState from "esoftplay/state";
import { Linking, Pressable, ScrollView, Text, View } from "react-native";



export interface EventOrder_detail_upgrade_paymentArgs {

}
export interface EventOrder_detail_upgrade_paymentProps {

}

export default function m(props: EventOrder_detail_upgrade_paymentProps): any {
  const { dataTicket, selectedTicket, fee_platform, fee_custom }: any = LibNavigation.getArgsAll(props)
  const [selectedPayment, setSelectedPayment] = BigbangPayment_listProperty.paymentState.useState()
  const [charge, setCharge] = useSafeState<any>(0)
  const [chargePercent, setChargePercent] = useSafeState<any>()

  const [trxId] = useSafeState(EventTransaction().getTrxId())
  const scrollRef = useRef<ScrollView>(null)
  const scrollYRef = useRef(0)
  const dialogSeat = useRef<LibSlidingup>(null)


  function doUpgrade(pin?: any) {
    const LibToastProperty = esp.modProp("lib/toast")
    if (!selectedPayment) {
      LibToastProperty.show(esp.lang("event/order_detail_upgrade_payment", "empty_method"))
      return
    }

    LibDialog.confirm(esp.lang("event/order_detail_upgrade_payment", "confirm_title"), esp.lang("event/order_detail_upgrade_payment", "confirm_msg", dataTicket?.price_name, selectedTicket?.selected_ticket?.price_name_to), esp.lang("event/order_detail_upgrade_payment", "confirm_ok"), () => {
      let post = {
        booking_id: dataTicket?.booking_id,
        price_id_to: selectedTicket?.selected_ticket?.price_id_to,
        trx_id: trxId,
        payment_id: selectedPayment?.payment_id,
        ...selectedPayment
      }

      if (selectedTicket?.selected_ticket?.use_seat == 1) {
        post.seat_label = selectedTicket?.seat_label?.join('|')
      }

      if (selectedTicket?.selected_ticket?.seat_autopick == 1) {
        post.adjacent_seats = 1
      }

      if (selectedPayment?.payment_id == 2) {
        post.pin = pin
      }
      LibProgress.show(esp.lang("event/order_detail_upgrade_payment", "confirm_wait"))
      new LibCurl(dataTicket?.url_upgrade || 'event_order_detail_upgrade_checkout', post, (res, msg) => {
        LibProgress.hide()
        LibNavigation.reset()
        if (res?.hasOwnProperty('url_mobile') && res?.url_mobile != null) {
          Linking.openURL(res?.url_mobile)
          LibNavigation.push('event/order_detail_waiting', { url: res?.url })
        } else if (res?.hasOwnProperty('url_web') && res?.url_web != null) {
          LibNavigation.navigateForResult('payment/cc_web', {
            ...res,
            statusSuccess: [1]
          }).then((res) => {
            LibNavigation.backToRoot()
            LibNavigation.push('user/profile')
            if (res?.hasOwnProperty('params_error') || res?.hasOwnProperty('failed')) {
              LibNavigation.push('event/order_waiting')
              LibNavigation.push('event/order_detail_waiting', { url: res?.url })
            } else {
              LibNavigation.push('event/order')
            }
          })
        } else {
          if (res?.url?.includes("waiting")) {
            LibNavigation.push('event/order_waiting')
          }
          LibNavigation.push(res?.url?.includes("waiting") ? 'event/order_detail_waiting' : 'event/order_detail', {
            url: res.url,
          })
        }

      }, (err) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/order_detail_upgrade_payment", "oops"), err?.message)
      })

    }, esp.lang("event/order_detail_upgrade_payment", "confirm_no"), () => { })

  }


  function percentageCalculator(amount: any, percent: any) {
    return (percent * amount) / 100
  }

  const price = Number(selectedTicket?.selected_ticket?.price_to || selectedTicket?.selected_ticket?.amount_difference)
  const qty = Number(dataTicket?.qty_upgrade)

  const calculate = PaymentFee_calculate(price, qty,
    {
      fee_platform_type: fee_platform?.fee_platform_type || "NONE",
      fee_platform_amount: fee_platform?.fee_platform_amount || 0,
      fee_custom_type: fee_custom?.fee_custom_type || "NONE",
      fee_custom_amount: fee_custom?.fee_custom_amount || 0,
      discount_type: "NONE",
      discount_amount: 0,
      tax: dataTicket?.tax_event || 0
    }
  )


  let amount = Number(selectedTicket?.selected_ticket?.price_to || selectedTicket?.selected_ticket?.amount_difference) * Number(dataTicket?.qty_upgrade)
  let subtotalWithTaxWithFeePlatform = calculate.subtotal

  let _charge = amount == 0 ? 0 : Number(charge)
  let _charge_percent = chargePercent == 0 ? 0 : percentageCalculator(subtotalWithTaxWithFeePlatform, chargePercent)
  let _charge_total = chargePercent ? _charge + _charge_percent : _charge

  let _amountTotal = Number(subtotalWithTaxWithFeePlatform) + Number(_charge_total)

  function renderSeatItem(item: any, i: number) {
    const seat = item.includes("#") ? item.split("#")[1] : item
    return (
      <View key={i} style={{ margin: 10, marginBottom: 0, marginRight: 5, marginLeft: 5, height: 32, width: 32, backgroundColor: LibStyle.colorBlue, borderWidth: 1, borderColor: LibStyle.colorBlue, borderRadius: 4, justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
        <Text allowFontScaling={false} adjustsFontSizeToFit style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#fff", textAlign: "center", textAlignVertical: "center" }}>{seat}</Text>
      </View>
    )
  }

  const currency = selectedTicket?.selected_ticket?.currency || "IDR"

  const itemData = useMemo(() => {
    const items: BigbangPayment_detail_ticketProperty.BigbangPayment_detail_ticketItem[] = []

    items.push({
      label: esp.lang("event/order_detail_upgrade_payment", "upgrade_to", dataTicket?.price_name, selectedTicket?.selected_ticket?.price_name_to),
      caption: dataTicket?.ondate != "0000-00-00" ? LibUtils.moment(dataTicket?.ondate).localeFormat("DD MMMM YYYY") : "",
      value: LibUtils.money(price, currency),
      qty: LibUtils.number(qty)
    })

    //seat
    const name_seat = selectedTicket?.seat_name
    if (name_seat && name_seat.length > 0) {
      const firstSeat = name_seat?.[0]
      const seat = firstSeat.includes("#") ? firstSeat.split("#")[1] : firstSeat
      items.push({
        label: esp.lang("bigbang/payment_detail", "text_seat"),
        value:
          <Pressable onPress={() => dialogSeat.current?.show()} style={{ flexDirection: 'row', justifyContent: 'center', alignContent: 'center', alignItems: 'center' }} >
            <View style={{ marginRight: 5, marginLeft: 5, height: 28, width: 28, backgroundColor: LibStyle.colorBlue, borderWidth: 1, borderColor: LibStyle.colorBlue, borderRadius: 4, justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
              <Text allowFontScaling={false} adjustsFontSizeToFit style={{ fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#fff", textAlign: "center", textAlignVertical: "center" }}>{seat}</Text>
            </View>
            {
              name_seat && name_seat?.length > 1 &&
              <LibIcon.MaterialIcons name="more" style={{ transform: [{ rotate: '180deg' }] }} size={37} color={LibStyle.colorBlue} />
            }
          </Pressable>
      })
    }

    // Gov tax
    if (dataTicket?.tax_event) {
      if (Number(dataTicket?.tax_event) !== 0) {
        items.push({
          label: esp.lang("bigbang/payment_detail", "tax", String(Number(dataTicket?.tax_event))),
          value: LibUtils.money(calculate.tax, currency)
        })
      } else
        //@ts-ignore
        items.push({
          caption: esp.lang("bigbang/payment_detail", "tax_include")
        })
    }

    // Platform fee
    if (calculate.platform !== 0) {
      items.push({
        label: esp.lang("bigbang/payment_detail", "fee_apps"),
        value: LibUtils.money(calculate.platform, currency),
        sublabel: (fee_platform?.fee_platform_type !== "NOMINAL") ? "(" + fee_platform?.fee_platform_amount + "%)" : ""
      });
    }

    // Custom fee
    if (calculate.custom !== 0) {
      items.push({
        label: fee_custom?.fee_custom_label || "Custom Fee",
        value: LibUtils.money(calculate.custom, currency),
        sublabel: (fee_custom?.fee_custom_type !== "NOMINAL") ? "(" + fee_custom?.fee_custom_amount + "%)" : ""
      });
    }

    //potongan sebelumnya
    if (dataTicket?.previous_total && dataTicket?.previous_total > 0) {
      items.push({
        label: esp.lang("bigbang/payment_detail_ticket", "previous_total"),
        value: "-" + LibUtils.money(dataTicket?.previous_total, currency),
      })
    }

    // Admin bank
    items.push({
      label: esp.lang("bigbang/payment_detail", "admin_fee"),
      sublabel: esp.modProp("bigbang/payment_detail_ticket").processAdminBank(chargePercent, charge, currency),
      caption: esp.lang("bigbang/payment_detail", "info"),
      value: LibUtils.money(_charge_total, currency),
    })

    return items
  }, [charge, chargePercent, _charge_total, dataTicket, calculate, price, qty])

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <EventHeader title={esp.lang("event/order_detail_upgrade_payment", "header_title")} />
      <ScrollView ref={scrollRef} stickyHeaderIndices={[0]} scrollEventThrottle={16} onScroll={({ nativeEvent }) => {
        const currentYPosition = nativeEvent.contentOffset.y
        const oldPosition = scrollYRef.current

        if (currentYPosition >= (LibStyle.height * 0.3)) {
          if (oldPosition == 0) {
            scrollYRef.current = nativeEvent.contentOffset.y
            BigbangPayment_detail_ticketProperty.stateShow.set(false)
          }
        }
      }}>

        {/* detail */}
        <View style={{ backgroundColor: 'white' }}>
          <BigbangPayment_detail_ticket
            product_title={esp.lang("event/order_detail_upgrade_payment", "upgrade_to", dataTicket?.price_name, selectedTicket?.selected_ticket?.price_name_to)}
            product_subtitle={dataTicket?.event_title}
            product_price={LibUtils.money(_amountTotal - (dataTicket?.previous_total || 0), currency)}
            itemData={itemData}
          />
        </View>


        <BigbangPayment_list
          eventId={dataTicket?.event_id}
          url_payment={dataTicket?.url_payment}
          previous_total={dataTicket?.previous_total || 0}
          onToggleCC={() => { scrollRef.current?.scrollToEnd({ animated: true }) }}
          order_type={14} // upgrade ticekt
          currency={selectedTicket?.selected_ticket?.currency}
          onPressPayment={(item: any) => {
            let payment = {
              ...item,
              payment_id: Number(item.id),
              payment_type: Number(item.type),
            }
            setSelectedPayment(payment)
            setCharge(item.charge)
            setChargePercent(item.charge_percent)
          }}
          paymentId={selectedPayment?.payment_id}
          priceTotal={Number(_amountTotal)}
          chargeTotal={_charge_total}
        />
      </ScrollView>
      <View style={{ padding: 10 }}>
        <EventButton label={esp.lang("event/order_detail_upgrade_payment", "pay")} onPress={() => {
          if (selectedPayment?.payment_id == 2) /* BBO PAY */ {
            LibNavigation.navigateForResult("bigbang/payment_pin", undefined, 1132).then((p) => {
              if (p) {
                doUpgrade(p)
              }
            })
          } else {
            doUpgrade()
          }
        }}
          fontColor='#fff'
          backgroundColor={selectedPayment ? "#00b894" : LibStyle.colorBgGrey}
        />
      </View>
      {/* ini dialog seat */}
      <LibSlidingup ref={dialogSeat}>
        <View style={{ backgroundColor: 'white', padding: 20 }} >
          <LibTextstyle text={esp.lang("bigbang/payment", "text_seat")} textStyle="headline" />
          <ScrollView >
            <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
              {
                selectedTicket?.seat_name?.map(renderSeatItem)
              }
            </View>
          </ScrollView>
        </View>
      </LibSlidingup>
    </View>
  )
}