// withHooks
import { EventExchange_ticketProperty } from 'esoftplay/cache/event/exchange_ticket/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventOrder_itemProperty } from 'esoftplay/cache/event/order_item/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/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 { 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 useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import React, { useEffect } from 'react';
import { Pressable, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventExchange_ticket_resultArgs {

}
export interface EventExchange_ticket_resultProps {

}


const listConfirmExchange = useGlobalState<any[]>([])

export function stateListConfirm(): useGlobalReturn<any> {
  return listConfirmExchange
}

export default function m(props: EventExchange_ticket_resultProps): any {
  const { qr, event_id, event_title }: any = LibNavigation.getArgsAll(props)
  const [listTicket, setListTicket, getListTicket] = useSafeState<any>()

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

  function logGift(res: any) {
    res.forEach((item: any) => { EventExchange_ticketProperty.addCounterGiftBy(item.title, 1) })
  }

  function loadData() {
    let url = "event_booking_exchange" + LibUtils.objectToUrlParam({
      event_id: event_id,
      code: encodeURIComponent(qr),
      t: new Date().getTime()
    })

    new LibCurl(url, null, (res, msg) => {
      EventExchange_ticketProperty.addCounterScan(1)
      setListTicket(res)
    }, (err) => {
      EventExchange_ticketProperty.addCounterScanNo(1)
      LibDialog.warningConfirm(esp.lang("event/exchange_ticket_result", "warn_title"), err?.message, esp.lang("event/exchange_ticket_result", "warn_ok"), () => { LibNavigation.back() }, "", () => { })
    }, 1)
  }

  function filterSelectedData(data: any) {
    return data.reduce((acc: any, item: any) => {
      if (item.selected == 1) {
        const listWithTitles = item.list.map((giftItem: any) => ({
          ...giftItem,
          title: item.title
        }));
        return acc.concat(listWithTitles);
      }
      return acc;
    }, []);
  }

  function exchangeTicket() {
    let url = "event_booking_exchange_confirm" + LibUtils.objectToUrlParam({ event_id: event_id, })
    let post = {
      ids: JSON.stringify(filterSelectedData(getListTicket()?.gifts).map((it: any) => it.id)),
    }

    logGift(filterSelectedData(getListTicket()?.gifts))
    let a = listConfirmExchange.get()
    let item = {
      post: post,
      url: url
    }


    let checkSame = a.filter((z: any) => z?.post?.ids == post?.ids)
    if (checkSame?.length == 0) {
      listConfirmExchange?.set(LibObject.push(a, item)())
      EventExchange_ticketProperty.subscribeSync().trigger(listConfirmExchange.get())
      LibDialog.confirm(esp.lang("event/exchange_ticket_result", "info_title"), esp.lang("event/exchange_ticket_result", "success_exchange"), esp.lang("event/exchange_ticket_result", "scan_againn"), () => {
        LibNavigation.back()
        LibNavigation.navigate('component/scanner', { event_title: event_title, event_id: event_id, fromPage: "event/exchange_ticket" })
      }, "", () => { })
    } else {
      esp.modProp("lib/toast").show(esp.lang("event/exchange_ticket_result", "ticket_claimed"))
    }
  }

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

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={qr} subtitle={event_title} />
      <ScrollView>
        <View style={{ margin: 10, padding: 10, backgroundColor: LibStyle.colorPrimary, borderRadius: 5, alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
          <Text allowFontScaling={false} style={{ fontWeight: 'bold', color: EventOrder_itemProperty.textColor(LibStyle.colorPrimary), fontSize: 50 }}>{LibUtils.number(listTicket?.qty_ticket)}</Text>
          <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode="tail" style={{ color: EventOrder_itemProperty.textColor(LibStyle.colorPrimary), textAlign: 'center', fontSize: 24 }}>{listTicket?.price_name}</Text>
          {
            listTicket?.hasOwnProperty("ondate") && listTicket?.ondate != "0000-00-00" &&
            <Text allowFontScaling={false} style={{ color: EventOrder_itemProperty.textColor(LibStyle.colorPrimary), marginTop: 5, textAlign: 'center', fontSize: 16 }}>{LibUtils.moment(listTicket?.ondate).format("DD MMM YYYY")}</Text>
          }
        </View>
        <View style={{ padding: 10, marginTop: 0, margin: 10, borderRadius: 5, backgroundColor: '#fff' }}>
          {
            listTicket?.gifts?.map((item: any, i: number) => {
              return (
                <View key={i} style={{ padding: 5, marginBottom: 7, borderRadius: 5, backgroundColor: LibStyle.colorBgGrey }}>
                  <View style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center', padding: 5 }}>
                    <View style={{ flex: 1, }}>
                      <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode="tail" style={{ fontSize: 16, fontWeight: 'bold', color: "#000" }}>{item?.title} </Text>
                      <Text allowFontScaling={false} style={{ fontSize: 18, marginTop: 4, letterSpacing: 1 }}>{item?.list?.filter?.((x: any) => x?.is_exchanged == 0)?.length || 0} {esp.lang("event/exchange_ticket_result", "available")}</Text>
                    </View>
                    {
                      item?.list?.[0].is_exchanged == 0 &&
                      <Pressable onPress={() => {
                        if (item?.is_exchangable == 1 && item?.list?.[0].is_exchanged == 0) {
                          let a = LibObject.set(listTicket, item.selected == 1 ? 0 : 1)('gifts', i, 'selected')
                          setListTicket(a)
                        } else {
                          LibToastProperty.show(esp.lang("event/exchange_ticket_result", "not_yet_exchange"))
                        }
                      }} style={{ marginLeft: 5, width: LibStyle.width / 5, height: 30, borderRadius: 5, ...LibStyle.elevation(2), alignContent: 'center', alignItems: 'center', justifyContent: 'center', backgroundColor: item.selected == 1 ? LibStyle.colorRed : LibStyle.colorGreen }}>
                        <Text allowFontScaling={false} style={{ fontWeight: 'bold', color: "#fff" }}>{item.selected == 1 ? esp.lang("event/exchange_ticket_result", "cancel") : esp.lang("event/exchange_ticket_result", "choose")}</Text>
                        {/* <LibIcon name={item.selected == 1 ? 'radiobox-marked' : 'radiobox-blank'} color={item.is_exchangable == 1 ? (item.selected == 1 ? LibStyle.colorGreen : "#000") : "#c9c9c9"} /> */}
                      </Pressable>
                    }

                  </View>

                  <View style={{ marginTop: 10, padding: 5, flexDirection: 'row' }}>
                    <View style={{ marginBottom: 5, flex: 1, padding: 5, backgroundColor: "#37c2d0", borderWidth: 1, borderColor: LibStyle.colorBgGrey, borderRadius: 5 }}>
                      <Text allowFontScaling={false} style={{ fontWeight: 'bold', color: '#fff', marginBottom: 5, fontSize: 14, }}>{esp.lang("event/exchange_ticket_result", "tms")}</Text>
                      {item?.list?.map((it: any, ii: number) => {
                        if (ii == 0) {
                          return (
                            <View key={ii} style={{ borderRadius: 5, margin: 2, padding: 5, backgroundColor: i % 2 ? '#fff' : LibStyle.colorGrey, borderBottomWidth: 1, borderBottomColor: LibStyle.colorBgGrey }}>
                              <Text allowFontScaling={false} style={{ paddingHorizontal: 5, fontSize: 13 }}>{it?.tms_name != "" ? it.tms_name : esp.lang("event/exchange_ticket_result", "not_redem")}</Text>
                            </View>
                          )
                        } else {
                          return null
                        }
                      })}
                    </View>
                    <View style={{ marginBottom: 5, flex: 1, padding: 5, backgroundColor: "#37c2d0", borderWidth: 1, borderColor: LibStyle.colorBgGrey, borderRadius: 5 }}>
                      <Text allowFontScaling={false} style={{ fontWeight: 'bold', color: '#fff', marginBottom: 5, fontSize: 14, }}>{esp.lang("event/exchange_ticket_result", "time_use")}</Text>
                      {item?.list?.map((it: any, ii: number) => {
                        if (ii == 0) {
                          return (
                            <View key={ii} style={{ borderRadius: 5, margin: 2, padding: 5, backgroundColor: i % 2 ? '#fff' : LibStyle.colorGrey, borderBottomWidth: 1, borderBottomColor: LibStyle.colorBgGrey }}>
                              <Text allowFontScaling={false} style={{ paddingHorizontal: 5, fontSize: 13 }}>{it?.exchanged_at != "" ? LibUtils.moment(it.exchanged_at).localeFormat("DD MMM HH:mm:ss ") : esp.lang("event/exchange_ticket_result", "not_redem")}</Text>
                            </View>
                          )
                        } else {
                          return null
                        }
                      })}
                    </View>
                  </View>

                </View>
              )
            })
          }
        </View>
      </ScrollView>
      <View style={{ padding: 10, backgroundColor: '#fff' }}>
        <TouchableOpacity onPress={() => {
          LibNavigation.back()
          LibNavigation.navigate('component/scanner', { event_title: event_title, event_id: event_id, fromPage: "event/exchange_ticket" })
        }}>
          <View style={{ height: 35, borderRadius: 5, borderWidth: 2, borderColor: LibStyle.colorRed, backgroundColor: "#fff", justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 }} >
            <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", textAlign: "center", textAlignVertical: 'center', color: LibStyle.colorRed, marginRight: 13, marginLeft: 10 }} >{esp.lang("event/exchange_ticket_result", "scan_again")}</Text>
          </View>
        </TouchableOpacity>

        {/* {
        listTicket?.list?.some((item: any) => item.exchanger_id == 0) && */}
        <TouchableOpacity onPress={() => {
          if (filterSelectedData(listTicket?.gifts).length > 0) {
            exchangeTicket()
          } else {
            LibToastProperty.show(esp.lang("event/exchange_ticket_result", "please_choose_first"))
          }
        }}>
          <View style={{ ...LibStyle.elevation(2), marginTop: 10, height: 35, borderRadius: 5, backgroundColor: filterSelectedData(listTicket?.gifts).length > 0 ? LibStyle.colorGreen : LibStyle.colorBgGrey, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 }} >
            <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", textAlign: "center", textAlignVertical: 'center', color: 'white', marginRight: 13, marginLeft: 10 }} >{esp.lang("event/exchange_ticket_result", "total_ticket", listTicket?.qty_ticket)}</Text>
          </View>
        </TouchableOpacity>
        {/* } */}
      </View>

    </View>
  )
}