// withHooks
import { applyStyle } from 'esoftplay';
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { EventOrder_detailProperty } from 'esoftplay/cache/event/order_detail/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 { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibTheme } from 'esoftplay/cache/lib/theme/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useLazyState from 'esoftplay/lazy';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';

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


export interface EventOrder_rescheduleArgs {

}
export interface EventOrder_rescheduleProps {

}

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

  const [result, setResult, getResult] = useLazyState<any>()
  const imgWidth = LibStyle.width - 30
  const imgHeight = imgWidth / 1080 * 647
  const [refreshing, setRefreshing] = useSafeState<boolean>(false);

  let defaultTabs = [
    {
      id: 1,
      title: /*reschedule*/esp.lang("event/order_reschedule", "reschedule")
    },
    {
      id: 2,
      title: /*refund*/esp.lang("event/order_reschedule", "refund")
    },
  ]
  const [activeTab, setActiveTab] = useLazyState<any>(1)


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

  function loadData() {
    new LibCurl(url, null, (res, msg) => {
      setResult(res)()
      setRefreshing(false)
    }, (error) => {
      setRefreshing(false)
      LibDialog.warning(esp.lang("event/order_reschedule", "load_err"), error?.message)
    }, 1)
  }

  function onRefresh() {
    setRefreshing(true)
    loadData()
  }

  function rescheduleTicket() {
    let a = getResult().booking_list?.map?.((item: any) => item.price_type?.filter?.((item1: any) => item1.check == 1))
    let _booking_ids = getResult().booking_list?.map?.((item: any) => {
      if (item.price_type?.some((x: any) => x.check == 1)) {
        return item.id
      }
    })

    let _date_ids = []
    for (let i = 0; i < a.length; i++) {
      const element = a[i];
      if (element)
        for (let j = 0; j < element.length; j++) {
          const element1 = element[j];
          _date_ids.push(element1.date_id)
        }
    }

    let filter_booking_ids = _booking_ids.filter((item: any) => item != null)

    let post = {
      booking_ids: JSON.stringify(filter_booking_ids),
      date_ids: JSON.stringify(_date_ids)
    }

    if (_date_ids.length == 0) {
      LibToastProperty.show(esp.lang("event/order_reschedule", "msg_error_choose_date_ticket"))
      return
    }

    LibDialog.warningConfirm(esp.lang("event/order_reschedule", "title_alert_reschedule"), esp.lang("event/order_reschedule", "msg_confirm_want_change_date_ticket"), esp.lang("event/order_reschedule", "btn_yes_alert_reschedule"), () => {
      LibProgress.show(esp.lang("event/order_reschedule", "msg_wait"))
      new LibCurl('event_booking_reschedule_process', post, (res, msg) => {
        LibProgress.hide()
        LibNavigation.backToRoot()
        LibNavigation.navigate('event/order')
        // LibNavigation.navigate('event/order_detail', { url: res.url })
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/order_reschedule", "process_er"), error?.message)
      }, 1)
    }, esp.lang("event/order_reschedule", "btn_cancel_alert_reschedule"), () => {

    })
  }

  function rescheduleSeat(booking_id: any, row_id: any, column_id: any, qty: any, ondate: string) {
    let ondates = new Array(Number(qty)).fill(ondate).join('|')

    let post = {
      booking_id: booking_id,
      row_id: row_id,
      column_id: column_id,
      ondate: ondates
    }
    LibProgress.show(esp.lang("event/order_reschedule", "msg_wait"))
    new LibCurl("event_booking_reschedule_seat", post, (res, msg) => {
      LibProgress.hide()
      // setMsgReseat(res)
      EventOrder_detailProperty.subscribe().trigger()
      LibDialog.info(esp.lang("event/order_reschedule", "title_success_reschedule_seat"), res)
    }, (error) => {
      LibDialog.warning(esp.lang("event/order_reschedule", "seat_err"), error?.message)
      LibProgress.hide()
    }, 1)
  }

  function refundTicket() {
    let a = getResult().booking_list?.filter?.((item: any) => item.check == 1)
    let _booking_ids: any[] = []

    for (let i = 0; i < a.length; i++) {
      const element = a[i];
      _booking_ids.push(element.id)
    }

    if (_booking_ids.length == 0) {
      LibToastProperty.show(esp.lang("event/order_reschedule", "msg_error_choose_ticket"))
      return
    }


    let post = {
      booking_ids: JSON.stringify(_booking_ids),
    }

    LibDialog.warningConfirm(esp.lang("event/order_reschedule", "warning"), esp.lang("event/order_reschedule", "refund_ticket_purchased"), esp.lang("event/order_reschedule", "btn_yes_refund_ticket"), () => {
      LibProgress.show(esp.lang("event/order_reschedule", "msg_wait"))
      new LibCurl('event_booking_reschedule_refund', post, (res, msg) => {
        LibProgress.hide()
        LibDialog.confirm(esp.lang("event/order_reschedule", "title_success_msg"), res, esp.lang("event/order_reschedule", "ok"), () => {
          LibNavigation.backToRoot()
        }, "", () => { })
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/order_reschedule", "refunc_err"), error?.message)
      }, 1)
    }, esp.lang("event/order_reschedule", "no"), () => {

    })
  }

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

  if (!result?.booking_list?.length) {
    return (
      <View style={{ flex: 1, backgroundColor: '#fff' }}>
        <EventHeader title={esp.lang("event/order_reschedule", "reschedule_or_refund_ticket")} />
        <EventMessage message={esp.lang("event/order_reschedule", "no_ticket_need_reschedule_or_refund")} />
      </View>
    )
  }

  function updateResult(item: any, i: number, item1: any, i1: number) {
    let a = LibObject.update(getResult(), (data) => {
      for (let j = 0; j < data.price_type.length; j++) {
        data.price_type[j].check = i1 == j ? data.price_type[j].hasOwnProperty("check") && data.price_type[j].check == 1 ? 0 : 1 : 0
      }
      return { ...data }
    })('booking_list', i)

    setResult(a)()


    if (item.reseat == 1) {
      let data = {
        event_id: getResult().id,
        qty: item.qty,
        // kenapa seperti ini, biar objeknya sama dengan di event/ticket_list
        selected_ticket: {
          list: {
            price_id: item.price_id,
            on_date: item.on_date
          }
        }
      }

      LibNavigation.navigateForResult('event/seat', {
        url: 'event_seat',
        dataTicket: data,
      }).then((value) => {
        rescheduleSeat(item.id, value.row_id, value.column_id, item.qty, item1.ondate)
      })
    }
  }

  function renderRescheduleList(item: any, i: number) {
    return (
      <View key={i}>
        <View style={applyStyle({ backgroundColor: '#f1f2f3', padding: 14, borderTopWidth: 3, borderTopColor: '#999', marginTop: 10 })}>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }} >
            <View style={{ flex: 2 }}>
              <Text style={applyStyle({ fontFamily: "Arial", fontSize: 12, lineHeight: 20, fontStyle: "normal", letterSpacing: 0 })} >{(item.price_name) + " (" + item.qty + " " + esp.lang("event/order_reschedule", "ticket_text")}<Text style={{ color: "orange" }} >{item.qty_shared > 0 ? esp.lang("event/order_reschedule", "shared", item?.qty_shared) : ""}</Text>{")"}</Text>
            </View>

            <View style={{ flex: 1, alignContent: 'flex-end', alignItems: 'flex-end' }}>
              <Text style={applyStyle({ fontFamily: "Arial", fontSize: 12, lineHeight: 20, fontStyle: "normal", fontWeight: 'bold', letterSpacing: 0 })} >{LibUtils.money(item.price)}</Text>
            </View>
          </View>
          {
            item.ondate != "0000-00-00" &&
            <Text style={applyStyle({ fontFamily: "Arial", fontSize: 12, lineHeight: 20, fontStyle: "normal", fontWeight: 'bold', letterSpacing: 0 })} >{esp.lang("event/order_reschedule", "date", moment(item.ondate).format("DD MMMM YYYY"))}</Text>
          }
          <Text style={applyStyle({ fontFamily: "Arial", fontSize: 12, lineHeight: 20, fontStyle: "normal", fontWeight: 'bold', letterSpacing: 0 })} >{esp.lang("event/order_reschedule", "select_new_date")}</Text>
        </View>

        {
          item?.price_type?.length > 0 && item.price_type.map((item1: any, i1: number) => {
            // let _selectTicket = selectedTicket == item1.date_id
            let _selectTicket = item1.hasOwnProperty('check') && item1.check == 1
            let bgDatePassed = item1.is_passed == 1 ? LibStyle.colorLightGrey : _selectTicket ? "#f6f6f6" : '#fff'
            let opacityPassed = item1.is_passed == 1 ? 0.5 : 1

            if (item1.date_id == "") {
              return (
                <TouchableOpacity onPress={() => {
                  if (item1.is_passed == 0) {
                    updateResult(item, i, item1, i1)
                  }
                }} key={i1} style={applyStyle({ overflow: 'hidden', flex: 1, backgroundColor: bgDatePassed, flexDirection: 'row', justifyContent: 'space-between', padding: 10 })}>
                  <View style={applyStyle({ flex: 1 })}>
                    <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0.23, color: _selectTicket ? "#3ea4dc" : '#999' })}>{item1.title}</Text>
                    <Text allowFontScaling={false} style={applyStyle({ marginTop: 4, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: _selectTicket ? "#3ea4dc" : '#999' })}>{item1.subtitle}</Text>
                  </View>
                  <TouchableOpacity onPress={() => {
                    if (item1.is_passed == 0) {
                      updateResult(item, i, item1, i1)
                    }
                  }} style={applyStyle({ padding: 8, opacity: 1 })} >
                    <LibIcon name={_selectTicket ? "checkbox-marked-circle" : "radiobox-blank"} size={22} style={{ opacity: opacityPassed }} color={_selectTicket ? "#3ea4dc" : "#434343"} />
                  </TouchableOpacity>
                </TouchableOpacity>
              )
            } else {
              let ticketLeft: any = Number(item1.quota) - Number(item1.quota_used)
              return (
                <TouchableOpacity key={i1} onPress={() => {
                  if (item1.is_passed == 0) {
                    updateResult(item, i, item1, i1)
                  }
                }} >
                  <View style={applyStyle({ overflow: 'hidden', opacity: 1, flex: 1, flexDirection: 'row', paddingLeft: 0, padding: 10, alignItems: 'center', backgroundColor: bgDatePassed })}>
                    <View style={applyStyle({ marginLeft: 14, marginHorizontal: 20, width: 42, height: 42, borderRadius: 5, backgroundColor: bgDatePassed, borderStyle: "solid", borderWidth: 1, borderColor: _selectTicket ? "#3ea4dc" : '#999', alignContent: 'center', alignItems: 'center', justifyContent: 'center' })}>
                      <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0.23, textAlign: "center", color: _selectTicket ? "#3ea4dc" : '#999', opacity: opacityPassed })}>{LibUtils.moment(item1.ondate).format('DD')}</Text>
                    </View>
                    <View style={applyStyle({ flexDirection: 'column', flex: 1 })}>
                      {
                        item.quota > 0 && ticketLeft <= 10 &&
                        <Text allowFontScaling={false} style={{ opacity: item.is_refundable == 1 ? 1 : 0.5, fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0.23, color: LibStyle.colorRed }}>{esp.lang("event/order_reschedule", "qty_left", ticketLeft)}</Text>
                      }
                      <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectTicket ? "#3ea4dc" : '#999', opacity: opacityPassed })}>{LibUtils.moment(item1.ondate).format('dddd')}</Text>
                      <View style={applyStyle({ flexDirection: 'row' })}>
                        <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectTicket ? "#3ea4dc" : '#999', opacity: opacityPassed })}>{LibUtils.moment(item1.ondate).format('MMMM')}</Text>
                        <Text allowFontScaling={false} style={applyStyle({ marginLeft: 7, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectTicket ? "#3ea4dc" : '#999', opacity: opacityPassed })}>{LibUtils.moment(item1.ondate).format('YYYY')}</Text>
                      </View>
                    </View>
                    <View style={applyStyle({ marginLeft: 10, flexDirection: 'column', marginRight: 6 })} >
                      {/* <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "right", color: _selectTicket ? "#3ea4dc" : '#999', opacity: opacityPassed })} >{LibUtils.money(item1.price, item1.currency)}</Text> */}
                    </View>

                    <TouchableOpacity onPress={() => {
                      if (item1.is_passed == 0) {
                        updateResult(item, i, item1, i1)
                      }
                    }} style={applyStyle({ padding: 8, opacity: 1 })} >
                      <LibIcon name={_selectTicket ? "checkbox-marked-circle" : "radiobox-blank"} size={22} style={{ opacity: opacityPassed }} color={_selectTicket ? "#3ea4dc" : "#434343"} />
                    </TouchableOpacity>

                  </View>
                </TouchableOpacity>
              )
            }
          })
        }

      </View>
    )
  }

  function renderRefundList(item: any, i: number) {
    let _selectTicket = item.hasOwnProperty('check') && item.check == 1
    const styleID_12nkjf: any = { marginLeft: 10, textDecorationLine: 'line-through', textDecorationStyle: 'solid', opacity: item.is_refundable == 1 ? 1 : 0.5, marginTop: 4, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: _selectTicket ? "#3ea4dc" : '#999' }
    return (
      <View key={i}>
        <TouchableOpacity onPress={() => {
          if (item.is_refundable == 1) {
            setResult(() => LibObject.set(getResult(), item.hasOwnProperty('check') && item.check == 1 ? 0 : 1)('booking_list', i, "check"))()
          }
        }} style={{ flex: 1, backgroundColor: item.is_refundable == 1 ? '#fff' : LibStyle.colorLightGrey, flexDirection: 'row', justifyContent: 'space-between', padding: 10 }}>
          <View style={applyStyle({ flex: 1 })}>
            {
              item.ondate != "0000-00-00" &&
              <Text style={applyStyle({ fontFamily: "Arial", fontSize: 12, lineHeight: 20, fontStyle: "normal", fontWeight: 'bold', letterSpacing: 0 })} >{esp.lang("event/order_reschedule", "ticket_date", moment(item.ondate).format("DD MMMM YYYY"))}</Text>
            }
            {item.qty_shared > 0 &&
              <LibTextstyle textStyle='caption1' text={esp.lang("event/order_reschedule", "chared", item.qty_shared)} style={{ color: 'orange' }} />
            }
            <Text allowFontScaling={false} style={{ opacity: item.is_refundable == 1 ? 1 : 0.5, fontFamily: "Arial", fontSize: 10, marginBottom: 4, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0.23, color: LibStyle.colorRed }}>{item.refund == "0.00" ? esp.lang("event/order_reschedule", "cant_refund") : esp.lang("event/order_reschedule", "refundable", LibUtils.numberAbsolute(item.refund).toString())}</Text>
            <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectTicket ? "#3ea4dc" : LibTheme._colorTextSecondary() })}>{esp.lang("ticket/refund", "ticket")} {item.price_name + " (" + item.qty + " " + esp.lang("ticket/refund", "ticket") + ") "}</Text>
            <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
              <View style={{ flexDirection: 'row', marginTop: 4, alignContent: 'center', alignItems: 'center' }}>
                <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 16, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: _selectTicket ? "#3ea4dc" : LibTheme._colorTextSecondary() })}>{LibUtils.money(item.total, item.currency)}</Text>
                {
                  item?.tax != "0" &&
                  <Text allowFontScaling={false} style={{ marginLeft: 10, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: LibTheme._colorTextTertiary() }}>{esp.lang("event/order_reschedule", "price+tax")}</Text>
                }
              </View>
              {
                item.refund != "0.00" && item.refund != "100.00" &&
                <Text allowFontScaling={false} style={styleID_12nkjf}>{LibUtils.money(item.price)}</Text>
              }
            </View>
          </View>
          <TouchableOpacity onPress={() => {
            if (item.is_refundable == 1) {
              setResult(() => LibObject.set(getResult(), item.hasOwnProperty('check') && item.check == 1 ? 0 : 1)('booking_list', i, "check"))()
            }
          }} style={applyStyle({ padding: 8, opacity: 1 })} >
            <LibIcon name={_selectTicket ? "checkbox-marked-circle" : "radiobox-blank"} size={22} style={{ opacity: item.is_refundable == 1 ? 1 : 0.5 }} color={_selectTicket ? "#3ea4dc" : "#434343"} />
          </TouchableOpacity>
        </TouchableOpacity>
      </View>
    )
  }


  const dateRange = LibUtils.getDateRange(result?.start_date, result?.end_date, " - ")

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={result?.global_refundable == 1 ? esp.lang("event/order_reschedule", "refund_rescedule") : esp.lang("event/order_reschedule", "rescedule")} />
      {
        result?.global_refundable == 1 &&
        <View style={{ margin: 15, padding: 3, borderRadius: 5, backgroundColor: '#fff', flexDirection: 'row' }}>
          {
            defaultTabs.map((item: any, i: number) => {
              let active = item.id == activeTab
              return (
                <TouchableOpacity
                  key={i}
                  onPress={() => {
                    loadData()
                    setActiveTab(item.id)()
                  }}
                  style={{ borderRadius: 5, padding: 5, alignContent: 'center', alignItems: 'center', justifyContent: 'center', flex: 1, backgroundColor: active ? LibStyle.colorPrimary : '#fff', marginRight: 1, marginLeft: 1 }}>
                  <Text allowFontScaling={false} style={{ fontSize: active ? 16 : 12, color: active ? "#fff" : "#000", fontWeight: active ? 'bold' : 'normal' }}>{item?.title}</Text>
                </TouchableOpacity>
              )
            })
          }
        </View>
      }

      <ScrollView refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }>
        <View style={{ marginTop: result?.global_refundable == 1 ? 0 : 10, margin: 15, borderRadius: 10, backgroundColor: '#fff', paddingBottom: activeTab == 2 ? 10 : 0 }}>
          {
            result?.image != "" &&
            <LibPicture source={{ uri: result?.image }} style={applyStyle({ height: imgHeight, width: imgWidth, resizeMode: 'cover' })} />
          }

          <View style={{ flexDirection: 'row', margin: 14, marginTop: 4, justifyContent: 'space-between' }}>
            <Text allowFontScaling={false} style={{ marginTop: 14, fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{result?.title}</Text>
          </View>

          <View style={{ margin: 14, marginTop: 0, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
            <LibIcon name="calendar-blank-outline" size={20} />
            <Text allowFontScaling={false} style={{ marginLeft: 6, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{dateRange}</Text>
          </View>

          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }} >
            <View style={{ width: 19, height: 19, borderRadius: 9.5, backgroundColor: LibStyle.colorBgGrey, marginLeft: -9.5 }} />
            <Text style={{ marginTop: 5, alignSelf: 'center', fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: "#f39c12" }} ></Text>
            <View style={{ width: 19, height: 19, borderRadius: 9.5, backgroundColor: LibStyle.colorBgGrey, marginRight: -9.5 }} />
          </View>

          {
            activeTab == 2 &&
            <View style={{ padding: 14, marginTop: 10, backgroundColor: '#f1f2f3' }}>
              <Text style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0 }} >{esp.lang("event/order_reschedule", "ready_ticket")}</Text>
            </View>
          }

          {
            result?.booking_list?.length > 0 && result?.booking_list.map(activeTab == 1 ? renderRescheduleList : renderRefundList)
          }
        </View>
      </ScrollView>

      {
        result?.is_reschedule == "1" &&
        <View style={{ padding: 10, flexDirection: 'row', justifyContent: 'center' }}>
          {
            activeTab == 1 ?
              <View style={{ width: LibStyle.width - 15 }}>
                <EventButton label={esp.lang("event/order_reschedule", "reschedule_ticket")} onPress={() => {
                  rescheduleTicket()
                }} backgroundColor="#e67e22" fontColor="#fff" />
              </View>
              :
              <View style={{ width: LibStyle.width - 15 }}>
                <EventButton label={esp.lang("event/order_reschedule", "refund_ticket")} onPress={() => {
                  refundTicket()
                }} backgroundColor={LibStyle.colorRed} fontColor="#fff" />
              </View>
          }
        </View>
      }

    </View >
  )
}