// withHooks
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import esp from 'esoftplay/esp';
import useLazyState from 'esoftplay/lazy';
import { useRef } from 'react';

import { EventFab } from 'esoftplay/cache/event/fab/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { LibInfinite } from 'esoftplay/cache/lib/infinite/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Pressable, Text, TouchableOpacity, View } from 'react-native';


export interface EventCoupon_claim_staffArgs {

}
export interface EventCoupon_claim_staffProps {

}
export default function m(props: EventCoupon_claim_staffProps): any {
  const { event_id, tenant_id } = esp.mod("lib/navigation").getArgsAll(props)
  const [userScan, setUserScan] = useLazyState<any>()
  const inputRef = useRef<LibInput>(null)
  const keywordRef = useRef<LibInput>(null)
  const scrollRef = useRef<LibInfinite>(null)
  const [key, setKey] = useSafeState(1)
  const [query, setQuery] = useSafeState("")
  const slidingAddRef = useRef<LibSlidingup>(null)

  function doAddUser() {
    const email: any = inputRef.current?.getText()

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

    const doAdd = () => {
      const curl = esp.mod("lib/curl")
      const post = {
        email: String(email).toLowerCase(),
        tenant_id,
        event_id
      }

      esp.mod("lib/progress").show(esp.lang("event/coupon_claim", "add_process"))
      new curl("event_coupon_tenant_add", post, (result, message) => {
        esp.modProp("lib/toast").show(message)
        esp.mod("lib/progress").hide()
        slidingAddRef.current?.hide()
        inputRef.current?.setText("")
        setKey(x => x + 1)
        scrollRef.current?.loadData()
      }, (error) => {
        esp.log(error);
        esp.mod("lib/progress").hide()
        esp.mod("lib/dialog").warning(esp.lang("event/coupon_claim", "warning_add_user"), error?.message)
      }, 1)
    }

    esp.mod('lib/dialog').confirm(esp.lang("event/coupon_claim", "confirm_add_user"),
      esp.lang("event/coupon_claim", "confirm_msg_add", email),
      esp.lang("event/coupon_claim", "confirm_add"), () => {
        doAdd()
      },
      esp.lang("event/coupon_claim", "confirm_cancel_add"), () => { })
  }


  function deleteUser(item: any, index: number) {

    const doDelete = () => {
      const curl = esp.mod("lib/curl")
      const post = { staff_id: item?.staff_id, event_id }

      esp.mod("lib/progress").show(esp.lang("event/coupon_claim", "deleting_user"))
      new curl("event_coupon_tenant_delete", post, (result, message) => {
        esp.modProp("lib/toast").show(message)
        esp.mod("lib/progress").hide()
        setUserScan((x: any) => esp.mod("lib/object").splice(x, index, 1)())()
      }, (error) => {
        esp.mod("lib/progress").hide()
        esp.mod("lib/dialog").warning(esp.lang("event/coupon_claim", "warning_delete"), error?.message)
      }, 1)

    }

    esp.mod('lib/dialog').warningConfirm(esp.lang("event/coupon_claim", "confirm_delete_user"),
      esp.lang("event/coupon_claim", "delete_user", item?.email),
      esp.lang("event/coupon_claim", "delete_user_ok"), () => {
        doDelete()
      },
      esp.lang("event/coupon_claim", "delete_user_cancel"), () => { })

  }

  function changeUserStatus(item: any, index: number) {
    const doChange = () => {
      const curl = esp.mod("lib/curl")
      const post = { staff_id: item?.staff_id, active: item?.active == true ? 0 : 1, event_id }

      esp.mod("lib/progress").show(esp.lang("event/coupon_claim", "nonactive_user"))
      new curl("event_coupon_tenant_active", post, (result, message) => {
        esp.log({ result, message });
        esp.mod("lib/progress").hide()
        esp.modProp("lib/toast").show(message)
        setUserScan((x: any) => esp.mod("lib/object").set(x, item?.active == true ? 0 : 1)(index, "active"))()
      }, (error) => {
        esp.mod("lib/progress").hide()
        esp.mod("lib/dialog").warning(esp.lang("event/coupon_claim", "warning_non_active"), error?.message)
      }, 1)
    }

    esp.mod('lib/dialog').warningConfirm(item?.active == true ? esp.lang("event/coupon_claim", "user_nonactive") : esp.lang("event/coupon_claim_staff", "activate_staff"),
      esp.lang("event/coupon_claim", "msg_change_status", item?.active == true ? esp.lang("event/coupon_claim", "msg_nonactive") : esp.lang("event/coupon_claim", "msg_active"), item?.email),
      `${item?.active == true ? esp.lang("event/coupon_claim", "noncative_confirm") : esp.lang("event/coupon_claim", "active_confirm")}`, () => {
        doChange()
      },
      esp.lang("event/coupon_claim", "cancel_change_status"), () => { })

  }

  function buildSearchUrl(url: string): string {
    if (query != "") {
      url += url.includes('?') ? '&' : '?'
      url += 'keyword=' + query
    }
    return url
  }

  function doSearch() {
    if (keywordRef.current?.getText?.() && keywordRef.current?.getText?.() != "") {
      const email = keywordRef.current?.getText?.()
      setQuery(email)
    }
  }

  return (
    <View style={{ flex: 1 }}>
      <EventHeader title={esp.lang("event/coupon_claim_staff", "manage_coupon")} subtitle={esp.lang("event/coupon_claim_staff", "manage_coupon_sub")} notif />

      <View style={{ marginHorizontal: 15, marginTop: 10, flexDirection: 'row', alignItems: 'center' }}>
        <LibInput
          ref={keywordRef}
          base
          defaultValue={query}
          placeholder={esp.lang("event/coupon_claim_history", "search_email")}
          onChangeText={(t) => { }}
          onSubmitEditing={() => doSearch()}
          style={{ flex: 1, borderColor: '#E6E6E6', color: '#B8B8B8', borderWidth: 1, padding: 4, paddingLeft: 40, borderRadius: 10, backgroundColor: 'white', height: 40 }}
        />
        <View style={{ position: "absolute", top: 9, bottom: 0, left: 9 }}>
          <LibIcon name="magnify" color="#E6E6E6" />
        </View>
        {
          query != "" &&
          <Pressable onPress={() => {
            setQuery("")
            keywordRef.current?.setText("")
          }} style={{ position: "absolute", top: 9, bottom: 0, right: 9 }}>
            <LibIcon name="close" color={LibStyle.colorRed} />
          </Pressable>
        }
      </View>

      <LibInfinite
        ref={scrollRef}
        key={buildSearchUrl("event_coupon_tenant_list?tenant_id=" + tenant_id)}
        url={buildSearchUrl("event_coupon_tenant_list?tenant_id=" + tenant_id)}
        errorView={(e: string) => <EventMessage message={e} />}
        isDebug={1}
        injectData={userScan}
        onDataChange={(data) => setUserScan(data)()}
        // key={key}
        extraData={key}
        renderItem={(item, index) => (
          <View key={index} style={[{ backgroundColor: "white", marginHorizontal: 15, marginBottom: 10, marginTop: 5, padding: 10, borderRadius: 10, flexDirection: "row", alignItems: "center" }, LibStyle.elevation(3)]}>
            <View style={{ flex: 1 }}>
              {
                item?.name && item?.name != "" &&
                <Text allowFontScaling={false} numberOfLines={1} style={{ fontFamily: "Arial", fontSize: 16, marginBottom: 5 }}>{esp.mod("lib/utils").ucwords(item?.name)}</Text>
              }
              <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14 }}>{String(item?.email).toLowerCase()}</Text>
              {
                item?.active == 0 &&
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, color: LibStyle.colorRed, marginTop: 5 }}>{esp.lang("event/coupon_claim", "nonactive")}</Text>
              }
            </View>
            <Pressable onPress={() => {
              esp.modProp("market/slidingup").add(
                <View style={{ backgroundColor: '#f6f6f6', borderTopRightRadius: 20, borderTopLeftRadius: 20, paddingBottom: 35, paddingHorizontal: 19, }}>
                  <Text allowFontScaling={false} style={{ marginTop: 26, marginBottom: 23, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, textAlign: "center", color: "#34495e" }}>{esp.lang("event/coupon_claim", "delete_user_item", String(item?.email).toLowerCase())}</Text>
                  <TouchableOpacity onPress={() => {
                    esp.modProp("market/slidingup").hide()
                    changeUserStatus(item, index)
                  }}
                    style={[{ alignItems: 'center', paddingLeft: 10, height: 50, borderRadius: 5, alignContent: 'center', justifyContent: 'center', backgroundColor: '#fff' }, LibStyle.elevation(2)]} >
                    <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b" }}>{esp.lang("event/coupon_claim", "change_status", item?.active == 1 ? esp.lang("event/coupon_claim", "msg_nonactive") : esp.lang("event/coupon_claim", "msg_active"))}</Text>
                  </TouchableOpacity>
                  <TouchableOpacity onPress={() => {
                    esp.modProp("market/slidingup").hide()
                    deleteUser(item, index)
                  }} style={[{ alignItems: 'center', marginTop: 15, paddingLeft: 10, height: 50, borderRadius: 5, alignContent: 'center', justifyContent: 'center', backgroundColor: LibStyle.colorRed }, LibStyle.elevation(2)]} >
                    <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#fff" }}>{esp.lang("event/coupon_claim_staff", "delete_user_scan")}</Text>
                  </TouchableOpacity>
                </View>
              )
              esp.modProp("market/slidingup").show()
            }}>
              <LibIcon name='delete' color={LibStyle.colorRed} />
            </Pressable>
          </View>
        )}
      />

      <EventFab icon={"account-plus"} colorBg={LibStyle.colorPrimary} onPress={() => slidingAddRef.current?.show?.()} />

      <LibSlidingup ref={slidingAddRef}>
        <View style={{ backgroundColor: "white", padding: 15, paddingBottom: 25, borderTopLeftRadius: 10, borderTopRightRadius: 10 }}>
          <View style={{ flexDirection: "row", alignItems: "center" }}>
            <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "ArialBold", fontSize: 14, color: "#6F442D" }}>{esp.lang("event/coupon_claim", "add_user_scan")}</Text>
            <Pressable onPress={() => slidingAddRef.current?.hide?.()}>
              <LibIcon name='close' color={LibStyle.colorRed} />
            </Pressable>
          </View>
          <View style={{ borderWidth: 1, borderColor: "#e6e6e6", height: 34, borderRadius: 10, marginVertical: 10 }}>
            <LibInput
              ref={inputRef}
              base
              placeholder={esp.lang("event/coupon_claim", "input_email")}
              onChangeText={() => { }}
              onSubmitEditing={doAddUser}
              returnKeyType='go'
              keyboardType='email-address'
              autoCapitalize='none'
              style={{ flex: 1, paddingHorizontal: 10 }}
            />
          </View>
          <Pressable onPress={doAddUser} style={{ backgroundColor: LibStyle.colorGreen, height: 34, alignItems: "center", justifyContent: "center", paddingHorizontal: 10, borderRadius: 10 }}>
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, color: "white" }}>{esp.lang("event/coupon_claim", "add_user_btn")}</Text>
          </Pressable>
        </View>
      </LibSlidingup>
    </View>
  )
}