// withHooks
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/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 { 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 { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/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 { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useGlobalState from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import { useRef } from 'react';

import { applyStyle } from 'esoftplay';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventLabel_input } from 'esoftplay/cache/event/label_input/import';
import useLazyState from 'esoftplay/lazy';
import React, { useEffect } from 'react';
import { ActivityIndicator, Platform, ScrollView, Text, TouchableOpacity, View } from 'react-native';



export interface EventVisitor_inputProps {
  navigation: any
}

const inputsState = useGlobalState<any>({})

export default function m(props: EventVisitor_inputProps): any {
  let _data: any = LibNavigation.getArgs(props, 'data')
  const { msg, url } = LibNavigation.getArgsAll(props)

  const [data, setData, getData] = useLazyState(_data)
  const [_msg, set_msg] = useSafeState(msg)
  const [messageGenerate, setMessageGenerate] = useSafeState<any>()
  const [activeTab, setActiveTab] = useSafeState(data?.list[0])
  const [counter, setCounter] = useSafeState(1)
  const [listClaim, setListClaim] = useSafeState()

  const dialogListClaim = useRef<LibSlidingup>(null)

  let _tabs: any = getData()?.list
  function setText(list_id: string): (name: string) => void {
    return (name) => inputsState.set(LibObject.set(inputsState.get(), name)(list_id))
  }

  // esp.log(url_invitation);

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

  function loadData(): void {
    new LibCurl(url, null, (result, msg) => {
      set_msg(msg)
      if (result?.hasOwnProperty('url_generate')) {
        generateCode(result?.url_generate, true)
      } else {
        setData(result)()
      }
    }, (error) => {
    })
  }

  function generateCode(url: string, loop: boolean) {
    if (loop) {
      new LibCurl(url, null, (res, msg) => {
        generateCode(url, res?.done == 1 ? false : true)
        setMessageGenerate(msg)
      }, (error) => {
        LibDialog.warningConfirm(esp.lang("event/visitor_input", "title"), error?.message, esp.lang("event/visitor_input", "resend"), () => {
          loadData()
        }, esp.lang("event/visitor_input", "back"), () => LibNavigation.back())
      })
    } else {
      loadData()
    }
  }

  function send(): void {
    var post: any = undefined
    const inputs = inputsState.get()
    post = {
      name: Object.values(inputs).join("|"),
      list_id: Object.keys(inputs).join("|")
    }
    LibDialog.confirm(esp.lang("event/visitor_input", "confirm_title"), esp.lang("event/visitor_input", "confirm_msg"), esp.lang("event/visitor_input", "confirm_ok"), () => {
      LibProgress.show(esp.lang("event/visitor_input", "confirm_wait"))
      new LibCurl('event_exhibitor_staff?contact_id=' + data.contact_id, post, (res, msg) => {
        LibProgress.hide()
        LibDialog.info(esp.lang("event/visitor_input", "confirm_success"), msg);
        LibNavigation.reset()
        // BigbangIndexProperty.setTab(0)
        // LibNavigation.navigate('bigbang/notif_index', { tabIndex: 0 }) // ini notifnya di perbarui
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("event/visitor_input", "confirm_failed"), error?.message)
      })
    }, esp.lang("event/visitor_input", "confirm_cancel"), () => { })
  }

  function renderTabs(item: any, i: number) {
    return (
      <TouchableOpacity key={i} onPress={() => {
        setActiveTab(item)
        setCounter(counter + 1)
      }}>
        <View style={applyStyle({ height: 35, width: LibStyle.width / 4, alignItems: 'center', overflow: 'visible', justifyContent: 'center', backgroundColor: '#fff' })}>
          <Text allowFontScaling={false} style={applyStyle({ width: LibStyle.width / 4, fontFamily: "Arial", fontSize: 11, fontWeight: activeTab?.id == item?.id ? "bold" : "normal", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: activeTab?.id == item?.id ? "#51b596" : "#c5c5c5" })}>{item.name} ({LibUtils.number(item?.qty)})</Text>
          <View style={applyStyle({ width: (LibStyle.width / 4) - 20, height: 3, backgroundColor: activeTab?.id == item?.id ? "#51b596" : "#fff", position: 'absolute', bottom: 0 })} />
        </View>
      </TouchableOpacity>
    )
  }

  function renderItem(item: any, i: any) {
    if (activeTab?.type == "INVITE") {
      let bgColor = Number(item.qty_used) != Number(item.qty) ? "#fff" : LibStyle.colorBgGrey
      let borderColor = Number(item.qty_used) != Number(item.qty) ? LibStyle.colorBgGrey : "#fff"
      return (
        <View style={{ margin: 15, marginBottom: 0, padding: 10, borderWidth: 1.5, backgroundColor: bgColor, borderColor: borderColor, borderRadius: 5 }}>
          <View style={{ flexDirection: 'row', flex: 1, justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
            <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b", }}>
              {esp.lang("event/visitor_input", "code_inv") + (i + 1)}
            </Text>
            {
              item.hasOwnProperty("url") && item.qty_used != 0 &&

              <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#51b596" }}>{LibUtils.number(item.qty_used) + "/" + LibUtils.number(item.qty)}</Text>
              // <View style={{ padding: 5, borderWidth: 1, borderColor: LibStyle.colorPrimary, borderRadius: 5 }}>
              // </View>
            }
            <TouchableOpacity activeOpacity={item.name == "" ? 0 : 1} onPress={() => {
              if (Number(item.qty_used) != Number(item.qty)) {
                LibUtils.copyToClipboard(item.access_code)
                LibToastProperty.show(esp.lang("event/visitor_input", "success_copy", item.access_code))
              }
            }}>
              <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: Number(item.qty_used) == Number(item.qty) ? "#c4c4c4" : "#2980b9" })}>{item.access_code}</Text>
                <LibIcon.Ionicons name='copy' size={16} style={applyStyle({ color: Number(item.qty_used) == Number(item.qty) ? "#c4c4c4" : "#2980b9", marginLeft: 7 })} />
              </View>
            </TouchableOpacity>
          </View>
          {
            item.hasOwnProperty("name") &&
            <Text allowFontScaling={false} style={{ marginTop: 5, fontFamily: "SFProText", color: '#4b4b4b' }}>{item?.name == "" ? esp.lang("event/visitor_input", "not_claimed") : item.name}</Text>
          }
          {
            item.hasOwnProperty("url") &&
            <View style={{ marginTop: 5, flexDirection: 'row', flex: 1 }}>
              {
                item.qty_used == 0 ?
                  <Text allowFontScaling={false} style={{ fontFamily: "SFProText", color: '#4b4b4b' }}>{esp.lang("event/visitor_input", "not_claimed")}</Text>
                  :
                  <View>
                    {/* <Text allowFontScaling={false} style={{ fontFamily: "SFProText", color: '#4b4b4b', marginBottom: 5 }}>{LibUtils.number(item.qty_used) + " sudah diklaim"}</Text> */}
                    <TouchableOpacity onPress={() => {
                      setListClaim(item)
                      LibUtils.debounce(() => {
                        dialogListClaim?.current?.show()
                      }, 200)
                    }} style={{ paddingHorizontal: 7, paddingVertical: 5, borderRadius: 5, borderWidth: 1, borderColor: LibStyle.colorBlue }}>
                      <Text allowFontScaling={false} style={{ color: LibStyle.colorBlue, fontWeight: 'bold', fontSize: 12 }}>{esp.lang("event/visitor_input", "see_list_claimed")}</Text>
                    </TouchableOpacity>
                  </View>
              }
            </View>
          }
        </View>
      )
    } else {
      return (
        <View style={applyStyle({ marginHorizontal: 15 })} >
          <View style={applyStyle({ flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' })}>
            <EventLabel_input label={esp.lang("event/visitor_input", "input_names", (i + 1))} />
            <TouchableOpacity onPress={() => {
              LibUtils.copyToClipboard(item.access_code)
              LibToastProperty.show(esp.lang("event/visitor_input", "success_copy", item.access_code))
            }}>
              <View style={applyStyle({ marginTop: 12, marginRight: 3, flexDirection: 'row', justifyContent: 'center', alignContent: 'center', alignItems: 'center' })}>
                <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: item.is_used == 1 ? "#c4c4c4" : "#2980b9" })}>{item.access_code}</Text>
                <LibIcon.Ionicons name='copy' size={16} style={applyStyle({ color: item.is_used == 1 ? "#c4c4c4" : "#2980b9", marginLeft: 7 })} />
              </View>
            </TouchableOpacity>
          </View>
          <EventInput_rectangle
            returnKeyType="next"
            key={activeTab?.id + "??" + i}
            editable={item.is_used == 0}
            style={applyStyle({ borderRadius: 4, borderColor: '#c4c4c4', height: 35, marginTop: 8, backgroundColor: item.is_used == 1 ? "#e9e9e9" : '#fff' })}
            defaultValue={item.name}
            onChangeText={setText(item.list_id)}
            placeholder={esp.lang("event/visitor_input", "placeholder_input_name", (i + 1))}
          />
        </View>
      )
    }
  }

  if (Number(getData()?.qty_generated) != Number(getData()?.qty)) {
    return (
      <View style={{ flex: 1, backgroundColor: '#fff' }}>
        <EventHeader title={esp.lang("event/visitor_input", "title_input_exhibitors")} />
        <View style={{ backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' }}>
          <View style={{ justifyContent: 'center', alignItems: 'center', padding: 10 }}>
            <LibPicture source={esp.assets('img_failed_msg.png')} resizeMode="contain" style={{ width: LibStyle.width * 0.8, height: 200, resizeMode: 'contain' }} />
            <ActivityIndicator size={'large'} color={LibStyle.colorPrimary} style={{ alignItems: 'center', justifyContent: 'center' }} />
            <View style={{ width: LibStyle.width - 40, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', padding: 15, borderRadius: 10, marginTop: 20 }}>
              <Text allowFontScaling={false} style={{ fontFamily: 'Arial', fontSize: 16, fontWeight: "bold", marginBottom: 5, color: "#4a4a4a", textAlign: "center" }}>{_msg}</Text>
            </View>
            <Text allowFontScaling={false} style={{ textAlign: 'center', fontFamily: "Arial", fontSize: 14, margin: 15, marginBottom: 0 }} >{messageGenerate}</Text>
          </View>
        </View>
      </View>
    )
  }

  return (
    <View style={{ flex: 1 }}>
      <EventHeader title={esp.lang("event/visitor_input", "title_input_exhibitor")} subtitle={esp.lang("event/visitor_input", "total_staff", LibUtils.number(data.qty))} />
      <LibKeyboard_avoid style={{ flex: 1 }}>
        <>
          {/* <ComponentTabheader titles={tabTitles} activeIndex={tabIndex} onPress={(index) => setTabIndex(index)} /> */}

          <View style={{ height: 35, marginBottom: 2, flexDirection: 'row', backgroundColor: '#fff', ...LibStyle.elevation(2) }} >
            <ScrollView horizontal showsHorizontalScrollIndicator={false} >
              {
                _tabs.map(renderTabs)
              }
            </ScrollView>
          </View>
          <LibInfinite
            url={activeTab?.url}
            // isDebug={1}
            key={activeTab + counter}
            // style={{ flex: 1 }}
            removeClippedSubviews={Platform.OS == 'android'}
            renderItem={renderItem}
          />
          {
            activeTab?.type == "STAFF" &&
            <EventButton style={{ backgroundColor: '#00b894', margin: 5 }} label={esp.lang("event/visitor_input", "save_btn")} onPress={() => { send() }} />
          }
        </>
      </LibKeyboard_avoid>
      <LibSlidingup ref={dialogListClaim}>
        <View style={{ backgroundColor: 'white', padding: 15, height: LibStyle.height * 0.7, borderTopLeftRadius: 5, borderTopRightRadius: 5 }} >
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
            <LibTextstyle text={esp.lang("event/visitor_input", "list_claimed")} textStyle="headline" />
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#51b596" }}>{LibUtils.number(listClaim?.qty_used) + "/" + LibUtils.number(listClaim?.qty)}</Text>
          </View>
          <LibInfinite
            url={listClaim?.url}
            // isDebug={1}
            // key={}
            removeClippedSubviews={Platform.OS == 'android'}
            renderItem={(item: any, i: number) => {
              return (
                <View key={i} style={{ padding: 10, borderBottomWidth: 1.5, borderBottomColor: LibStyle.colorBgGrey, flexDirection: 'row' }}>
                  <Text allowFontScaling={false} style={{ fontSize: 16 }}>{(i + 1) + ". "}</Text>
                  <View>
                    <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode='tail' style={{ fontSize: 16 }}>{item.name}</Text>
                    <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode='tail'>{item.email}</Text>
                  </View>
                </View>
              )
            }}
          />
        </View>
      </LibSlidingup>
    </View>
  )
}