// withHooks
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import moment from 'esoftplay/moment';
import { useRef } from 'react';

import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInfinite } from 'esoftplay/cache/lib/infinite/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/import';
import esp from 'esoftplay/esp';
import useLazyState from 'esoftplay/lazy';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Pressable, Text, View } from 'react-native';


export interface EventCoupon_generateArgs {

}
export interface EventCoupon_generateProps {

}
export default function m(props: EventCoupon_generateProps): any {
  const { event_id, event_name, image } = LibNavigation.getArgsAll(props)
  const [data, setData] = useLazyState<any>()
  const [error, setError] = useLazyState<string>("")
  const [t, setT] = useSafeState<number>(new Date().getTime())
  const inputEmailRef = useRef<LibInput>(null)
  const inputNominalRef = useRef<LibInput>(null)
  const inputDescRef = useRef<LibInput>(null)

  const infiniteRef = useRef<LibInfinite>(null)

  const [coupon, setCoupon, getCoupon] = useLazyState<any>()

  const imgWidth = LibStyle?.width - 50
  const imgHeight = imgWidth / 1920 * 1080

  function load() {
    const curl = esp.mod("lib/curl")
    const url = "event_coupon_admin_detail?event_id=" + event_id + "&coupon_id=" + getCoupon()?.coupon_id
    new curl(url, null, (result, message) => {
      setData(result)()
    }, (error) => {
      setError(error?.message)
    }, 1)
  }

  function doSendVoucher() {
    const email: any = inputEmailRef.current?.getText()
    const amount = inputNominalRef.current?.getText()
    const notes = inputDescRef.current?.getText()

    if (email == "") {
      esp.modProp("lib/toast").show(esp.lang("event/coupon_generate", "email_empty"))
      return
    }
    let reg = /^[\w-.]+@([\w-]+.)+[\w-]{2,4}$/;
    if (email && reg.test(email) === false) {
      esp.modProp("lib/toast").show(esp.lang("event/coupon_generate", "email_invalid"))
      return
    }

    let post: any = {
      event_id,
      coupon_id: getCoupon()?.coupon_id,
      user_email_to: email,
      amount: amount || 0
    }

    if (notes != "") {
      post["notes"] = notes
    }

    const doSend = () => {
      esp.mod("lib/progress").show(esp.lang("event/coupon_generate", "send_progress", email))
      const curl = esp.mod("lib/curl")
      new curl("event_coupon_admin_send", post, (result, message) => {
        load()
        setT(new Date().getTime())
        inputEmailRef.current?.setText("")
        inputNominalRef.current?.setText("")
        inputDescRef.current?.setText("")
        esp.mod("lib/progress").hide()
        esp.modProp("lib/toast").show(message)
      }, (error) => {
        esp.mod("lib/progress").hide()
        esp.mod("lib/dialog").warning(esp.lang("event/coupon_generate", "send_failed"), error?.message)
      }, 1)
    }

    esp.mod("lib/dialog").confirm(esp.lang("event/coupon_generate", "send_title"), esp.lang("event/coupon_generate", "send_msg", email), esp.lang("event/coupon_generate", "send_btn"), () => {
      doSend()
    }, esp.lang("event/coupon_generate", "send_cancel"), () => { })

  }

  function buildUrl(url: string) {
    if (event_id) {
      url += url.includes('?') ? '&' : '?'
      url += 'event_id=' + event_id
    }
    if (getCoupon()?.coupon_id) {
      url += url.includes('?') ? '&' : '?'
      url += 'coupon_id=' + getCoupon()?.coupon_id
    }
    if (t) {
      url += url.includes('?') ? '&' : '?'
      url += 't=' + t
    }
    return url
  }

  return (
    <View style={{ flex: 1 }}>
      <EventHeader title={esp.lang("event/coupon_generate", "header")} subtitle={event_name} />
      <LibKeyboard_avoid style={{ flex: 1 }} >
        <LibScroll onRefresh={() => infiniteRef.current?.loadData()}>
          <View style={[{ backgroundColor: "white", marginHorizontal: 15, marginTop: 15, padding: 10, borderRadius: 10 }, LibStyle.elevation(3)]}>
            <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 14 }}>{event_name}</Text>

            <View style={[{ marginTop: 5, borderRadius: 10, backgroundColor: '#fff' }, LibStyle.elevation(2)]}>
              <LibPicture source={{ uri: image }} resizeMode="cover" style={{ height: imgHeight, width: imgWidth, borderRadius: 10, backgroundColor: "#f1f1f1" }} />
            </View>
          </View>

          <View style={[{ backgroundColor: "white", marginHorizontal: 15, marginTop: 15, marginBottom: 10, padding: 10, borderRadius: 10 }, LibStyle.elevation(3)]}>

            {
              coupon &&
              <View style={[{ marginBottom: 4, borderRadius: 10, backgroundColor: '#fff' }, LibStyle.elevation(2)]}>
                <LibPicture source={{ uri: coupon?.image }} resizeMode="cover" style={{ height: (LibStyle.width - 50) * 0.43, width: LibStyle.width - 50, borderRadius: 10, backgroundColor: "#f1f1f1" }} />
                <View style={{ backgroundColor: "rgba(0, 0, 0, 0.5)", position: 'absolute', borderBottomLeftRadius: 10, borderBottomRightRadius: 10, bottom: 0, left: 0, right: 0, padding: 10 }}>
                  <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#fff" }}>{coupon?.coupon_title}</Text>
                </View>
                <View style={{ position: 'absolute', top: (((LibStyle.width - 50) * 0.43) / 2) - 10, marginBottom: 15, flexDirection: 'row', justifyContent: 'space-between' }} >
                  <View style={{ width: 23, height: 23, borderRadius: 11.5, backgroundColor: "white", marginLeft: -9.5 }} />
                  <View style={{ flex: 1 }} />
                  <View style={{ width: 23, height: 23, borderRadius: 11.5, backgroundColor: "white", marginRight: -9.5 }} />
                </View>
              </View>
            }

            <Pressable onPress={() => {
              esp.mod("lib/navigation").navigateForResult("event/coupon_generate_list", { event_id }, 120).then((value) => {
                setCoupon(value)()
                load()
              })
            }} style={{ borderWidth: 1, borderColor: "#e6e6e6", height: 40, borderRadius: 10, marginTop: 10, flexDirection: "row", alignItems: "center", paddingHorizontal: 10 }}>
              {
                coupon ?
                  <>
                    <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 14, flex: 1 }}>{coupon?.coupon_title}</Text>
                    <LibIcon name='pencil' size={18} />
                  </>
                  : <>
                    <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "ArialBold", fontSize: 14, color: "#999999" }}>{esp.lang("event/coupon_generate", "select_coupon")}</Text>
                    <LibIcon name='chevron-right' />
                  </>
              }
            </Pressable>
            <View style={{ borderWidth: 1, borderColor: "#e6e6e6", height: 40, borderRadius: 10, marginTop: 10, flexDirection: "row", alignItems: "center", paddingHorizontal: 10 }}>
              <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, color: "#4b4b4b" }} >Rp. </Text>
              <LibInput
                ref={inputNominalRef}
                base
                placeholder={esp.lang("event/coupon_generate", "input_nominal")}
                placeholderTextColor='#999999'
                onChangeText={() => { }}
                keyboardType='numeric'
                mask='###.###.###.###.###.###.###.###.###.###'
                maskFrom='end'
                returnKeyType='next'
                onSubmitEditing={() => {
                  inputEmailRef.current?.focus()
                }}
                style={{ flex: 1, paddingHorizontal: 5 }}
              />
            </View>
            <View style={{ borderWidth: 1, borderColor: "#e6e6e6", height: 40, borderRadius: 10, marginTop: 10, flexDirection: "row", alignItems: "center", paddingHorizontal: 10 }}>
              <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, color: "#4b4b4b" }} >@ </Text>
              <LibInput
                ref={inputEmailRef}
                base
                placeholder={esp.lang("event/coupon_generate", "input_email")}
                placeholderTextColor='#999999'
                onChangeText={() => { }}
                keyboardType='email-address'
                returnKeyType='next'
                onSubmitEditing={() => {
                  inputDescRef.current?.focus()
                }}
                style={{ flex: 1, paddingHorizontal: 10 }}
              />
            </View>
            <View style={{ borderWidth: 1, borderColor: "#e6e6e6", height: 80, borderRadius: 10, marginVertical: 10 }}>
              <LibInput
                ref={inputDescRef}
                base
                placeholder={"notes"}
                placeholderTextColor='#999999'
                multiline
                onChangeText={() => { }}
                returnKeyType='go'
                onSubmitEditing={doSendVoucher}
                style={{ flex: 1, padding: 10, textAlignVertical: "top" }}
              />
            </View>
            <Pressable
              onPress={() => {
                if (getCoupon()) {
                  doSendVoucher()
                } else {
                  esp.modProp("lib/toast").show(esp.lang("event/coupon_generate", "select_coupon_alert"))
                }
              }}
              style={{ backgroundColor: coupon ? LibStyle.colorGreen : "#e6e6e6", height: 40, alignItems: "center", justifyContent: "center", paddingHorizontal: 10, borderRadius: 10 }}>
              <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, color: "white" }}>{esp.lang("event/coupon_generate", "btn_send")}</Text>
            </Pressable>
            {
              data &&
              <View style={{ marginTop: 10, flexDirection: "row", alignItems: "center", justifyContent: "space-between" }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, color: "#606060" }}>{esp.lang("event/coupon_generate", "quota_left")}</Text>
                <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 16, letterSpacing: 1 }}>{`${data?.qty_claimed} / ${data?.qty}`}</Text>
              </View>
            }
          </View>
          {
            data && coupon &&
            <LibInfinite
              ref={infiniteRef}
              key={coupon?.coupon_id + buildUrl("event_coupon_admin_claimed")}
              url={buildUrl("event_coupon_admin_claimed")}
              errorView={(error: any) => (
                <EventMessage message={error} />
              )}
              renderItem={(item, index) => (
                <View key={index} style={[{ backgroundColor: "white", marginHorizontal: 15, marginTop: 10, marginBottom: 5, padding: 10, borderRadius: 10, flexDirection: "row", alignItems: "center" }, LibStyle.elevation(3)]}>
                  <View style={{ width: 36, height: 36, borderRadius: 18, backgroundColor: "#909090", alignItems: "center", justifyContent: "center" }}>
                    <LibIcon name='send' size={20} color='#f1f1f1' />
                  </View>
                  <View style={{ flex: 1, marginLeft: 10 }}>
                    <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, marginBottom: 5 }}>{item?.coupon_title}</Text>
                    {
                      item?.amount && item?.amount != "" && item?.amount != 0 &&
                      <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 14 }}>{LibUtils.money(item?.amount)}</Text>
                    }
                    <View style={{ flexDirection: "row", marginVertical: 5 }}>
                      <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "Arial", fontSize: 12 }}>{String(item?.user_email).toLowerCase()}</Text>
                      <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, color: "#606060" }}>{moment(item?.claimed_time).localeFormat("DD MMM YYYY HH:mm:ss")}</Text>
                    </View>
                    {
                      item?.notes && item?.notes != "" &&
                      <Text allowFontScaling={false} style={{ marginTop: 3, fontFamily: "Arial", fontSize: 12, color: "#606060", letterSpacing: 1 }}>{item?.notes}</Text>
                    }
                  </View>
                </View>
              )}
            />
          }
        </LibScroll>
      </LibKeyboard_avoid>
    </View>
  )
}