// withHooks
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventIndexProperty } from 'esoftplay/cache/event/index/import';
import { EventOrder_detailProperty } from 'esoftplay/cache/event/order_detail/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 { LibLoading } from 'esoftplay/cache/lib/loading/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 { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import { useEffect } from 'react';

import React from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventOrder_detail_returnArgs {

}
export interface EventOrder_detail_returnProps {

}
export default function m(props: EventOrder_detail_returnProps): any {
  const { url } = LibNavigation.getArgsAll(props)

  const [result, setResult] = useSafeState()
  const [dataUser, setDataUser] = useSafeState()
  const [dataTicket, setDataTicket] = useSafeState()
  const [useAll, setUseAll] = useSafeState<boolean>(false)
  const [trxId] = useSafeState(EventTransaction().getTrxId())

  useEffect(() => {
    loadData()
  }, [])

  function loadData() {
    new LibCurl(url, null, (res, msg) => {
      setResult(res)
      if (res?.sharer_email != "") {
        loadDataUser(res?.sharer_email)
      }

      if (res?.hasOwnProperty('url_share')) {
        loadDataTicket(res?.url_share, res?.price_name)
      }
    }, (err) => {
      LibDialog.warning("Oops", err?.message)
      LibNavigation.back()
    })
  }

  function loadDataTicket(url: any, price_name: string) {
    new LibCurl(url, null, (res) => {
      let data = res?.length > 0 && res?.map((item: any, i: number) => {
        return ({
          ...item,
          checked: i == 0 ? 1 : 0,
          price_name: price_name
        })
      })
      // esp.log({ data });
      setDataTicket(data)
    }, (error) => {
      LibDialog.warning(esp.lang("event/order_share_to", "load_error"), error?.message);
    }, 1)
  }

  function loadDataUser(email: string) {
    let post: any = {
      email: email
    }
    new LibCurl("user_search", post, (res) => {
      setDataUser(res)

    }, (error) => {
      LibDialog.warning(esp.lang("event/order_share_to", "load_error"), error?.message);
    })
  }

  function sendBack(p: any) {
    LibDialog.confirm(esp.lang("event/order_detail", "warning"), esp.lang("event/order_detail", "return_this_ticket"), esp.lang("event/order_detail", "btn_yes"), () => {
      let _bookingMemberId = dataTicket?.filter((item: any) => item.checked == 1).map((it: any) => it.id)

      LibProgress.show(esp.lang("event/order_detail", "please_wait"))
      let post = {
        booking_member_id: _bookingMemberId.join('|'),
        trx_id: trxId,
        pin: p
      }
      new LibCurl('event_booking_shared_return?booking_id=' + result?.id + '&qty_shared=' + dataTicket?.filter((item: any) => item.checked == 1).length, post, (res: any, msg: any) => {
        // LibNotify(res)
        EventOrder_detailProperty.subscribe().trigger()
        EventIndexProperty.reload.trigger() //reload data order
        LibProgress.hide()
        LibDialog.info(esp.lang("event/order_detail", "information"), msg)
        LibNavigation.back()
      }, (error: any) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/order_detail", "back_err"), error?.message);
        LibNavigation.back()
      }, 1)
    }, esp.lang("event/order_detail", "btn_cancel"), () => { })
  }


  if (!result) {
    return <LibLoading />
  }

  let checkNotUsed = dataTicket?.length > 0 && dataTicket?.filter((x: any) => x?.checked == 0)

  return (
    <View style={{ flex: 1 }}>
      <EventHeader title={esp.lang("event/order_detail_return", "send_back_ticket")} />
      <ScrollView style={{ padding: 15 }}>

        <Text allowFontScaling={false} style={{ color: '#4a4a4a', fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0 }}>{"Tiket akan dikembalikan kepada"}</Text>
        <View style={{ marginVertical: 15, flexDirection: 'row' }}>
          <LibPicture source={{ uri: dataUser?.image }} style={{ height: 40, width: 40, borderRadius: 20 }} />
          <View style={{ marginLeft: 10 }}>
            <Text style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", color: "#4a4a4a" }} >{dataUser?.name}</Text>
            <Text style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", color: "#b7b7b7" }} >{dataUser?.email}</Text>
          </View>
        </View>

        <Text allowFontScaling={false} style={{ marginBottom: 10, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 1.5, color: "#000" }}>{"PILIH TIKET"}</Text>

        {
          dataTicket?.length > 0 && dataTicket?.map((item: any, i: number) => {
            const [front, end] = item?.seat_name?.split("#") || ["", ""];
            return (
              <TouchableOpacity key={i} onPress={() => {
                let a = LibObject.set(dataTicket, item.checked == 1 ? 0 : 1)(i, 'checked')
                setDataTicket(a)
                setUseAll(false)

              }} style={{ padding: 10, marginBottom: 10, borderRadius: 4, borderColor: item?.checked == 1 ? LibStyle.colorGreen : '#f1f1f1', borderWidth: 1, flexDirection: 'row' }}>
                <View style={{ flex: 5 }}>
                  <Text allowFontScaling={false} style={{ fontSize: 14, fontStyle: "normal", color: "#000", fontWeight: "bold", }}>{item?.price_name}</Text>
                  {/* seat */}
                  {
                    item?.seat_name != "" &&
                    <View style={{ marginVertical: 10 }}>
                      <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, marginBottom: 5, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "seat_number")}</Text>

                      <View style={{ marginLeft: 7, flexDirection: 'row' }}>
                        <View style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 5, paddingHorizontal: 5, backgroundColor: '#f1f1f1', borderRadius: 5, marginRight: 7 }}>
                          <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 16, color: "#000" }}> {front}</Text>
                          <Text allowFontScaling={false} style={{ marginLeft: 3, fontWeight: 'bold', fontSize: 16, color: '#000', }}>{end}</Text>
                        </View>
                      </View>
                    </View>
                  }
                  {/* add ons */}
                  {
                    item?.addons?.length > 0 &&
                    <View style={{ marginBottom: 5 }}>
                      <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{"Addons"}</Text>
                    </View>
                  }
                  {
                    item?.addons?.length > 0 && item?.addons?.map((x: any, ii: number) => {
                      return (
                        <View key={ii} style={{ marginLeft: 7, flexDirection: 'row' }}>
                          <View style={{}}>
                            <Text allowFontScaling={false} style={{ color: '#484848', fontSize: 12, fontWeight: 'bold', fontFamily: "Arial" }}>- {
                              x?.list?.map((y: any) => y).join(', ')
                            }</Text>
                            {
                              x?.ondate != "0000-00-00" &&
                              <Text allowFontScaling={false} style={{ marginLeft: 7, marginBottom: 3, marginTop: 3, fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: '#484848' }}>{
                                LibUtils.moment(x?.ondate).localeFormat('DD MMM YYYY')}</Text>
                            }
                          </View>
                        </View>
                      )
                    })
                  }


                </View>
                <View style={{ flex: 1, alignContent: 'flex-end', alignItems: 'flex-end' }}>
                  <LibIcon name={item?.checked == 1 ? 'check-circle' : 'radiobox-blank'} color={LibStyle.colorGreen} />
                </View>
              </TouchableOpacity>
            )
          })
        }

      </ScrollView>

      <View style={{ marginHorizontal: 15, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'space-between' }}>
        <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode={'tail'} style={{ fontWeight: 'bold', fontSize: 14, letterSpacing: 1 }}>{dataTicket?.filter((item: any) => item.checked == 1).length + " Tiket digunakan"}</Text>
        <TouchableOpacity onPress={() => {
          let a = dataTicket?.map((item: any, i: number) => {
            return { ...item, checked: useAll ? 0 : 1 }
          })
          setDataTicket(a)
          setUseAll(useAll ? false : true)
        }} style={{ paddingHorizontal: 15, paddingRight: 10, marginTop: 10, borderWidth: 1, borderColor: 'rgba(0, 0, 0, 0)', height: 25, borderRadius: 5, backgroundColor: (useAll || checkNotUsed?.length == 0) ? LibStyle.colorRed : LibStyle.colorGreen, flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center' }} >
          <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: '#fff', marginRight: 15 }} >{(useAll || checkNotUsed?.length == 0) ? esp.lang("event/order_detail_share", "cancel") : esp.lang("event/order_detail_share", "select_all")}</Text>
          <LibIcon.Ionicons size={18} color="#fff" name={(useAll || checkNotUsed?.length == 0) ? "close" : "checkmark-done"} />
        </TouchableOpacity>
      </View>

      <EventButton
        label={"Kembalikan tiket"}
        onPress={() => {
          LibNavigation.navigateForResult("bigbang/payment_pin", undefined, 1132).then((p) => {
            if (p) {
              sendBack(p)
            }
          })
        }}
        backgroundColor={"#fff"}
        borderColor={LibStyle.colorPrimary}
        fontColor={LibStyle.colorPrimary}
        style={{ borderRadius: 5, marginHorizontal: 15, margin: 10 }}
      />

    </View>
  )
}