// withHooks
import { EventCounter_requestProperty } from 'esoftplay/cache/event/counter_request/import';
import { LibAutoreload } from 'esoftplay/cache/lib/autoreload/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 { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/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 { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import { useTimeout } from 'esoftplay/timeout';

import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventQr_bg } from 'esoftplay/cache/event/qr_bg/import';
import LottieView from "lottie-react-native";
import React, { useEffect, useRef } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import QRCode from 'react-native-qrcode-svg';


export interface EventCounter_request_detailArgs {

}
export interface EventCounter_request_detailProps {

}
export default function m(props: EventCounter_request_detailProps): any {
  let { url, status_user } = LibNavigation.getArgsAll(props)
  const user = UserClass.state().get()
  const [result, setResult] = useSafeState<any>()
  const animation = useRef<LottieView>(null)
  const timeout = useTimeout()

  useEffect(() => {
    loadData()
    LibAutoreload.set(() => {
      loadData()
    })
    return () => LibAutoreload.clear()
  }, [])

  function loadData() {
    new LibCurl(url, null, (res, msg) => {
      setResult(res)
      timeout(() => {
        animation.current?.play()
      }, 300);
    }, (error) => {
      LibDialog.warning(esp.lang("event/counter_request_detail", "load_failed"), error?.message)
      LibNavigation.back()
    }, 1)
  }

  function acceptRequest(url: string) {
    LibDialog.confirm(esp.lang("event/counter_request_detail", "acc_title"), esp.lang("event/counter_request_detail", "acc_msg"), esp.lang("event/counter_request_detail", "acc_confirm"), () => {
      LibProgress.show(esp.lang("event/counter_request_detail", "acc_wait"))
      new LibCurl(url, null, (res, msg) => {
        EventCounter_requestProperty.subscribe().trigger()
        LibProgress.hide()
        LibDialog.info(esp.lang("event/counter_request_detail", "acc_ok"), msg)
        LibNavigation.back()
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/counter_request_detail", "acc_no"), error?.message)
      }, 1)
    }, esp.lang("event/counter_request_detail", "acc_cancel"), () => {

    })
  }

  function cancelRequest(url: string) {
    LibDialog.confirm(esp.lang("event/counter_request_detail", "cancel_title"), esp.lang("event/counter_request_detail", "cancel_msg"), esp.lang("event/counter_request_detail", "cancel_confirm"), () => {
      LibProgress.show(esp.lang("event/counter_request_detail", "cancel_wait"))
      new LibCurl(url, null, (res, msg) => {
        EventCounter_requestProperty.subscribe().trigger()
        LibProgress.hide()
        LibDialog.info(esp.lang("event/counter_request_detail", "cancel_ok"), msg)
        LibNavigation.back()
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/counter_request_detail", "cancel_no"), error?.message)
      }, 1)
    }, esp.lang("event/counter_request_detail", "cancel_cancel"), () => {

    })
  }

  if (!result) {
    return (
      <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
        <EventHeader title={esp.lang("event/counter_request_detail", "header_loading")} />
        <LibLoading />
      </View>
    )
  }

  let isCoEo = user?.is_eo?.length > 0 && user?.is_eo?.find((item: any, i: number) => item.id == result?.event_id)

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/counter_request_detail", "header_title")} />

      <LibScroll onRefresh={loadData}>
        <View style={{ margin: 15, padding: 15, ...LibStyle.elevation(2), borderRadius: 5, backgroundColor: '#fff', }}>
          <View style={{ alignItems: 'center' }} >
            <Text allowFontScaling={false} style={{ marginBottom: 23, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, textAlign: "center", color: result?.status == 1 ? '#e99222' : result?.status == 2 ? '#57d24e' : result?.status == 3 ? '#c53030' : '#091440' }}>{
              result?.status == 1 ? esp.lang("event/counter_request_detail", "status_1") : result?.status == 2 ? esp.lang("event/counter_request_detail", "status_2") : result?.status == 3 ? esp.lang("event/counter_request_detail", "status_3") : esp.lang("event/counter_request_detail", "status_expired")
            }</Text>

            <LottieView
              ref={animation}
              loop={false}
              style={{
                width: 150,
                height: 150,
              }}
              source={esp.assets(result?.status == 1 ? 'pending.json' : result?.status == 2 ? 'success.json' : result?.status == 3 ? 'canceled.json' : 'expired.json')}
            // OR find more Lottie files @ https://lottiefiles.com/featured
            // Just click the one you like, place that file in the 'assets' folder to the left, and replace the above 'require' statement
            />
          </View>
          <Text style={{ alignSelf: 'center', textAlign: 'center', fontFamily: 'ArialBold', fontSize: 17, marginTop: 10, color: '#4a4a4a' }} >{result?.title}</Text>
          <Text style={{ alignSelf: 'center', textAlign: 'center', fontFamily: 'Arial', fontSize: 13, marginTop: 15, color: '#999' }} >{LibUtils.moment(result?.created).serverFormat('dddd, DD MMMM YYYY HH:mm')}</Text>
          {
            result?.amount != 0 &&
            <Text style={{ alignSelf: 'center', textAlign: 'center', fontFamily: 'ArialBold', fontSize: 25, marginTop: 10, color: LibStyle.colorPrimary }} >{esp.lang("event/counter_request_detail", "all_ticket", result?.hasOwnProperty("saldo") ? LibUtils.money(result?.amount) : LibUtils.number(result?.amount))}</Text>
          }

          <LibTextstyle text={esp.lang("event/counter_request_detail", "text_from")} textStyle="m_overline" style={{ color: '#999', marginTop: 20 }} />
          <View style={{ flexDirection: 'row', marginTop: 5, alignItems: 'center' }} >
            <LibPicture style={{ height: 40, width: 40, borderRadius: 20, backgroundColor: '#f1f2f3', marginRight: 20 }} source={result?.sender_image == "" ? esp.assets('icons/ic_no_image_merchant.png') : { uri: result?.sender_image }} />
            <View style={{ flex: 1 }} >
              <LibTextstyle text={result?.sender_name} textStyle={'body'} />
            </View>
          </View>
          <LibTextstyle text={esp.lang("event/counter_request_detail", "text_receiver")} textStyle="m_overline" style={{ color: '#999', marginTop: 15 }} />
          <View style={{ flexDirection: 'row', marginTop: 5, alignItems: 'center' }} >
            <LibPicture style={{ height: 40, width: 40, borderRadius: 20, backgroundColor: '#f1f2f3', marginRight: 20 }} source={result?.receiver_image == "" ? esp.assets('icons/ic_no_image_merchant.png') : { uri: result?.receiver_image }} />
            <View style={{ flex: 1 }} >
              <LibTextstyle text={result?.receiver_name} textStyle={'body'} />
              {
                LibUtils.checkUndefined(result, 'receiver_account') &&
                <LibTextstyle text={result?.receiver_account} textStyle={'footnote'} style={{ color: "#888" }} />
              }
            </View>
          </View>
          {
            result.notes != '' &&
            <>
              <LibTextstyle text={esp.lang("event/counter_request_detail", "message")} textStyle="m_overline" style={{ color: '#999', marginTop: 30, marginBottom: 5, }} />
              <LibTextstyle text={result.notes} textStyle={'body'} style={{}} />
            </>
          }
          {
            result?.hasOwnProperty("info") && result?.info != '' &&
            <View style={{ flexDirection: 'row', borderRadius: 10, backgroundColor: '#FEFBEB', borderColor: "#FFCC29", borderWidth: 1, borderStyle: 'dashed', alignContent: 'center', alignItems: 'center', flex: 1, marginTop: 15, padding: 10 }} >
              <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0 }} >{result?.info}</Text>

            </View>
          }

          {
            (result?.sender_id == user?.id || isCoEo?.eo_id == result?.sender_id) && (result?.sender_type == status_user) && result?.status == 1 &&
            <>
              <View style={{ borderRadius: 10, backgroundColor: '#FEFBEB', borderColor: "#FFCC29", borderWidth: 1, borderStyle: 'dashed', alignContent: 'center', alignItems: 'center', flex: 1, marginTop: 15, padding: 10 }}>
                <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0 }} >{esp.lang("event/counter_request_detail", "msg_scan", result?.title)}</Text>
              </View>
              <EventQr_bg>
                <View style={{ margin: 15, alignSelf: 'center' }}>
                  <QRCode ecl="H" size={LibStyle.width - 60} value={result?.url_receiver} />
                </View>
              </EventQr_bg>
            </>
          }
        </View>
        <View />
      </LibScroll>

      <View style={{ padding: 10 }}>

        {
          (result?.receiver_id == user?.id || isCoEo?.eo_id == result?.receiver_id) && (!status_user || result?.receiver_type == status_user) && result?.status == 1 ?
            <TouchableOpacity onPress={() => {
              acceptRequest(result?.url_accept)
            }} >
              <View style={{ width: LibStyle.width - 20, backgroundColor: LibStyle.colorGreen, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center' }} >
                <Text style={{ color: 'white', fontFamily: 'ArialBold', fontSize: 13 }} >{esp.lang("event/counter_request_detail", "btn_accept")}</Text>
              </View>
            </TouchableOpacity>
            :
            (result?.sender_id == user?.id || isCoEo?.eo_id == result?.sender_id) && (result?.sender_type == status_user) && result?.status == 1 &&
            <TouchableOpacity onPress={() => {
              cancelRequest(result?.url_cancel)
            }} >
              <View style={{ width: LibStyle.width - 20, backgroundColor: LibStyle.colorRed, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center' }} >
                <Text style={{ color: 'white', fontFamily: 'ArialBold', fontSize: 13 }} >{esp.lang("event/counter_request_detail", "btn_cancel")}</Text>
              </View>
            </TouchableOpacity>
        }

      </View>

    </View>
  )
}