// withHooks
import { LibInfinite } from 'esoftplay/cache/lib/infinite/import';
import { useRef } from 'react';

import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { EventSection_menu } from 'esoftplay/cache/event/section_menu/import';
import { EventSheet } from 'esoftplay/cache/event/sheet/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/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 { UseCondition } from 'esoftplay/cache/use/condition/import';
import esp from 'esoftplay/esp';
import useLazyState from 'esoftplay/lazy';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Pressable, Text, TouchableOpacity, View } from 'react-native';


export interface EventCoupon_claim_historyArgs {

}
export interface EventCoupon_claim_historyProps {
  hideHeader?: boolean, config: any, event_id: string
}
export default function m(props: EventCoupon_claim_historyProps): any {
  const { event_id, config } = esp.mod("lib/navigation").getArgsAll(props)
  let lastDate = useRef('')

  const usedConfig = props?.config || config
  const usedEventId = props?.event_id || event_id

  const baseURL = "event_coupon_tenant_redeemed_staff?event_id=" + usedEventId + "&tenant_id=" + usedConfig?.tenant_id

  const date_start = moment().localeFormat("YYYY-MM-DD")
  const date_end = moment().localeFormat("YYYY-MM-DD")
  const [selectedDate, setSelectedDate] = useSafeState<any>({ date_start, date_end })
  const [state, setState] = useSafeState<any>()
  const [query, setQuery] = useSafeState<string>("")
  const [staff, setStaff] = useLazyState<any>(usedConfig?.is_parent == 1 ? undefined : { staff_id: usedConfig?.staff_id })
  const [typeIndex, setTypeIndex] = useLazyState<any>(usedConfig?.is_parent == 1 ? 0 : 1)
  const headerShow = props?.hideHeader ? !props?.hideHeader : true
  const slidingRef = useRef<LibSlidingup>(null)
  const slidingDataRef = useRef<LibSlidingup>(null)
  const inputRef = useRef<LibInput>(null)

  const type = [esp.lang("event/coupon_claim_history", "all_data"), esp.lang("event/coupon_claim_history", "only_me")]

  function buildUrl(url: string): string {
    if (selectedDate?.date_start != "") {
      url += url.includes('?') ? '&' : '?'
      url += 'date_start=' + selectedDate?.date_start
    }
    if (selectedDate?.date_end != "") {
      url += url.includes('?') ? '&' : '?'
      url += 'date_end=' + selectedDate?.date_end
    }
    if (staff?.staff_id) {
      url += url.includes('?') ? '&' : '?'
      url += 'staff_id=' + staff?.staff_id
    }
    return url
  }

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

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

  const HeaderItem = (props: any) => {
    return (
      <View style={{ paddingHorizontal: 17, paddingVertical: 10, flexDirection: 'row', backgroundColor: LibUtils.hexToRgba(LibStyle.colorPrimary, 0.2), ...props?.containerStyle }} >
        <View style={{ flex: 1 }} >
          <LibTextstyle textStyle={"caption2"} text={esp.lang("event/coupon_claim_history", "date")} style={{ color: "#888" }} />
          <LibTextstyle textStyle={"callout"} text={props?.date} />
          <LibTextstyle textStyle={"caption2"} text={esp.lang("event/coupon_claim_history", "total_claim")} style={{ color: "#888", marginTop: 10 }} />
          <LibTextstyle textStyle={"callout"} text={props?.qty} />
        </View>
        <View style={{ flex: 1, alignItems: "flex-end" }} >
          <LibTextstyle textStyle={"caption2"} text={esp.lang("event/coupon_claim_history", "total")} style={{ color: "#888" }} />
          <LibTextstyle textStyle={"callout"} text={props?.amount} style={{ fontWeight: "bold" }} />
        </View>
      </View>
    )
  }

  return (
    <View style={{ flex: 1 }}>
      {
        headerShow &&
        <EventHeader title={esp.lang("event/coupon_claim_history", "header")} />
      }
      <View>
        <Pressable onPress={() => {
          LibNavigation.navigateForResult('feed/talent_date', { minDate: moment().add(-5, 'years').localeFormat('YYYY-MM-DD'), maxDate: moment().add(1, 'years').localeFormat('YYYY-MM-DD') }).then((item) => {
            setSelectedDate(item)
          })
        }} style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <View style={{ flex: 1, padding: 10, paddingHorizontal: 20, borderBottomWidth: 1, borderBottomColor: '#e9ecef', }}>
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/coupon_claim_history", "date_start")}</Text>
            <Text allowFontScaling={false} style={{ marginTop: 4, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{LibUtils.moment(selectedDate?.date_start).localeFormat("DD MMM YYYY")}</Text>
          </View>
          <View style={{ flex: 1, padding: 10, paddingHorizontal: 20, borderBottomWidth: 1, borderBottomColor: '#e9ecef', }}>
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/coupon_claim_history", "date_end")}</Text>
            <Text allowFontScaling={false} style={{ marginTop: 4, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{LibUtils.moment(selectedDate?.date_end).localeFormat("DD MMM YYYY")}</Text>
          </View>
        </Pressable>
        {
          usedConfig?.is_parent == 1 &&
          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
            <Pressable onPress={() => {
              slidingRef?.current?.show()
            }} style={{ flex: 1, padding: 10, paddingHorizontal: 20, borderBottomWidth: 1, borderBottomColor: '#e9ecef', flexDirection: "row", alignItems: "center" }}>
              <View style={{ flex: 1 }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/coupon_claim_history", "scan_staff")}</Text>
                <Text allowFontScaling={false} numberOfLines={1} ellipsizeMode='middle' style={{ marginTop: 4, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{staff?.email || esp.lang("event/coupon_claim_history", "staff")}</Text>
              </View>
              <LibIcon.SimpleLineIcons name="arrow-down" size={15} />
            </Pressable>
            <Pressable onPress={() => {
              slidingDataRef.current?.show()
            }} style={{ flex: 1, padding: 10, paddingHorizontal: 20, borderBottomWidth: 1, borderBottomColor: '#e9ecef', flexDirection: "row", alignItems: "center" }}>
              <View style={{ flex: 1 }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/coupon_claim_history", "show_data")}</Text>
                <Text allowFontScaling={false} style={{ marginTop: 4, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{type[typeIndex]}</Text>
              </View>
              <LibIcon.SimpleLineIcons name="arrow-down" size={15} />
            </Pressable>
          </View>
        }
      </View>
      <LibInfinite
        isDebug={1}
        key={buildUrl(baseURL)}
        url={buildUrl(baseURL)}
        onRefresh={() => lastDate.current = ""}
        errorView={(e: string) =>
          <EventMessage message={e} />
        }
        onResponseEdit={(res) => {
          let out = res.report
          setState(out)
          if (res?.report?.list.length > 0) {
            out = esp.mod("lib/object").update(res?.report, (list) => list.map((item: any) => {
              const used_at = moment(item.used_at).format("DD MMMM YYYY")
              const showDate = lastDate.current != used_at
              lastDate.current = used_at
              return { ...item, showDate: showDate }
            }))('list')
          }
          return out
        }}
        renderItem={(item: any, idx: number) => {
          return (
            <View key={idx}>
              <UseCondition if={idx === 0} >
                <HeaderItem
                  date={state?.date_end == state?.date_start ? moment(state?.date_start).localeFormat("dddd, DD MMMM YYYY") : LibUtils.getDateRange(state?.date_start, state?.date_end, " - ")}
                  qty={LibUtils.number(state?.qty)}
                  amount={LibUtils.money(state?.amount)} />
              </UseCondition>
              <UseCondition if={item?.showDate} >
                <EventSection_menu title={moment(item?.used_at).format("dddd, DD MMMM YYYY")} />
              </UseCondition>
              <View style={{ backgroundColor: "#f4f4f4", height: 2 }} />
              <TouchableOpacity
                onPress={() => { }}
                style={{ flexDirection: "row", paddingHorizontal: 17, paddingTop: 10, paddingBottom: 8 }} >
                <View style={{ flex: 1 }} >
                  <View style={{ flexDirection: "row", alignItems: "center" }} >
                    <LibIcon.Ionicons name="ticket" size={12} color="#888" />
                    <LibTextstyle textStyle="caption1" text={item?.title + " (" + item?.event_name + ")"} style={{ color: "#888", marginLeft: 5 }} />
                  </View>
                  <View style={{ flexDirection: 'row', alignItems: 'center' }} >
                    <LibTextstyle textStyle="caption1" text={item?.code} style={{ color: LibStyle.colorBlue }} />
                  </View>
                  <LibTextstyle textStyle="caption1" text={"QTY " + item?.qty} style={{ color: "#888" }} />
                  <LibTextstyle textStyle="caption1" text={LibUtils.moment(item?.used_at).serverFormat("DD MMMM YYYY H:mm:ss")} style={{ color: "#888" }} />
                </View>
                <View>
                  <LibTextstyle textStyle="caption1" text={item?.email_tenant} style={{ color: "#888", textAlign: "right" }} />
                  <LibTextstyle textStyle="footnote" text={LibUtils.money(item?.amount_total)} style={{ textAlign: "right" }} />
                </View>
              </TouchableOpacity>
            </View>
          )
        }}
      />

      <EventSheet
        _ref={slidingDataRef}
        title={esp.lang("event/coupon_claim_history", "show_data")}
        options={[
          ...type.map((x, i) => ({
            text: x, onPress: () => {
              setTypeIndex(i)()
              setStaff(() => i == 1 ? { staff_id: usedConfig?.staff_id } : undefined)
            }
          }))
        ]}
      />

      <LibSlidingup ref={slidingRef}>
        <View style={{ minHeight: LibStyle.height * 0.3, maxHeight: LibStyle.height * 0.6, backgroundColor: "white", paddingTop: 10 }}>
          <View style={{ marginHorizontal: 15, marginTop: 10, flexDirection: 'row', alignItems: 'center' }}>
            <LibInput
              ref={inputRef}
              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("")
                inputRef.current?.setText("")
              }} style={{ position: "absolute", top: 9, bottom: 0, right: 9 }}>
                <LibIcon name="close" color={LibStyle.colorRed} />
              </Pressable>
            }
          </View>

          <LibInfinite
            key={buildSearchUrl("event_coupon_tenant_list_history?tenant_id=" + usedConfig?.tenant_id)}
            url={buildSearchUrl("event_coupon_tenant_list_history?tenant_id=" + usedConfig?.tenant_id)}
            errorView={(e: string) => <EventMessage message={e} />}
            isDebug={1}
            ListHeaderComponent={
              <>
                {
                  !query &&
                  <Pressable onPress={() => {
                    setStaff(undefined)
                    slidingRef.current?.hide()
                  }} style={[{ backgroundColor: "white", marginHorizontal: 15, marginBottom: 5, marginTop: 10, padding: 10, borderRadius: 10, flexDirection: "row", alignItems: "center" }, LibStyle.elevation(3)]}>
                    <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14 }}>{esp.lang("event/coupon_claim_history", "all_staff")}</Text>
                  </Pressable>
                }
              </>
            }
            renderItem={(item, index) => (
              <Pressable onPress={() => {
                setStaff(item)()
                slidingRef.current?.hide()
              }} key={index} style={[{ backgroundColor: "white", marginHorizontal: 15, marginBottom: 5, marginTop: 10, padding: 10, borderRadius: 10 }, LibStyle.elevation(3)]}>
                {
                  item?.name && item?.name != "" &&
                  <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 16, marginBottom: 3 }}>{esp.mod("lib/utils").ucwords(item?.name)}</Text>
                }
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14 }}>{String(item?.email).toLowerCase()}</Text>
              </Pressable>
            )}
          />
        </View>
      </LibSlidingup>
    </View>
  )
}