// withHooks
import { useEffect, useRef } from 'react';

import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/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 { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Keyboard, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventQc_idcardArgs {

}
export interface EventQc_idcardProps {

}

export function openScanner(event_id: any) {
  LibNavigation.navigateForResult('component/scanner').then((value: any) => {
    if (value) {
      let post = {
        qr: value,
        event_id: event_id
      }
      LibProgress.show(esp.lang("event/qc_idcard", "wait"))
      new LibCurl('event_exhibitor_qc', post, (res, msg) => {
        LibProgress.hide()
        LibNavigation.navigate('event/qc_idcard_success', {
          data: { ...res.data },
          event_id: event_id
        })
      }, (err) => {
        LibProgress.hide()
        LibNavigation.navigate('event/qc_idcard_failed', {
          message: err?.message,
          result: err?.result,
          event_id: event_id
        })
      }, 1)
    }
  })
}

export default function m(props: EventQc_idcardProps): any {
  const { data } = LibNavigation.getArgsAll(props)

  const [result, setResult] = useSafeState<any>()
  const [error, setError] = useSafeState<any>()
  const [query, setQuery] = useSafeState<any>()
  const [showReset, setShowReset] = useSafeState<boolean>(false)
  const [counter, setCounter] = useSafeState(1)
  const [refreshing, setRefreshing] = useSafeState<boolean>(false);
  const dialogDetailExhibitor = useRef<LibSlidingup>(null)

  const [selectedExhibitor, setSelectedExhibitor] = useSafeState<any>()

  function loadData() {
    let post = {
      event_id: data?.id
    }
    let url = query ? 'event_exhibitor_qc_report?search=' + query : 'event_exhibitor_qc_report'
    LibProgress.show(esp.lang("event/qc_idcard", "wait"))
    new LibCurl(url, post, (res, msg) => {
      setResult(res)
      setError(undefined)
      setRefreshing(false)
      LibProgress.hide()
    }, (err) => {
      setRefreshing(false)
      LibProgress.hide()
      setResult(undefined)
      setError(err)
    }, 1)
  }

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

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


  function renderItem(item: any, i: number) {
    return (
      <TouchableOpacity onPress={() => {
        setSelectedExhibitor(item)
        LibUtils.debounce(() => {
          dialogDetailExhibitor?.current?.show()
        }, 100)
      }} key={i} style={{ ...LibStyle.elevation(2), marginBottom: 5, margin: 10, backgroundColor: '#fff', borderRadius: 5 }}>
        <View style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: LibStyle.colorGrey, flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode='tail' style={{ flex: 3, fontWeight: 'bold', fontSize: 16 }}>{item?.exhibitor_name}</Text>
          <Text allowFontScaling={false} style={{ flex: 1, fontWeight: 'bold', textAlign: 'right', fontSize: 16 }}>{LibUtils.number(item?.qty)}</Text>
        </View>
      </TouchableOpacity>
    )
  }


  function onRefresh() {
    setRefreshing(true)
    loadData()
  }

  if (!result && !error) {
    return <LibLoading />
  }

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title='QC ID CARD' subtitle={data?.name} />
      {/* <Image source={{ uri: 'https://static.vecteezy.com/system/resources/previews/005/594/108/non_2x/mobile-application-for-scanning-qr-code-hand-holding-smartphone-scan-qr-code-icon-phone-app-barcode-scanner-vector.jpg' }} style={{ flex: 1, opacity: 0.3, resizeMode: 'cover' }} /> */}
      <View style={{ backgroundColor: '#fff', padding: 16, paddingBottom: 10, }} >
        <View style={{ flexDirection: 'row' }}>
          <EventInput_rectangle
            style={{ marginTop: 0, borderRadius: 5, flex: 1, height: 38 }}
            placeholder={esp.lang("event/qc_idcard", "search_exhibitor")}
            onChangeText={(e) => {
              LibUtils.debounce(() => {
                setQuery(e)
              }, 200)
            }}
            blurOnSubmit
            returnKeyType='go'
            onSubmitEditing={() => {
              if (query?.trim()) {
                setCounter(counter + 1)
                setShowReset(true)
              }
            }}
          />
          <TouchableOpacity onPress={() => {
            if (query) {
              setCounter(counter + 1)
              Keyboard.dismiss()
              setShowReset(true)
            }
          }} style={{ marginLeft: 5, height: 38, width: 38, backgroundColor: LibStyle.colorGreen, alignContent: 'center', justifyContent: 'center', alignItems: 'center', borderRadius: 5 }}>
            <LibIcon name='magnify' color='#fff' />
          </TouchableOpacity>
        </View>
        {
          showReset &&
          <TouchableOpacity onPress={() => {
            setQuery(undefined)
            setCounter(counter + 1)
            setShowReset(false)
          }} style={{ flexDirection: 'row' }}>
            <View style={{ marginTop: 10, flexDirection: 'row', alignContent: 'center', alignItems: 'center', backgroundColor: LibStyle.colorRed, paddingVertical: 4, padding: 7, borderRadius: 5 }} >
              <LibTextstyle textStyle="caption1" text={query} style={{ color: 'white' }} />
              <LibIcon name='close-circle' style={{ marginLeft: 8 }} color="#fff" size={15} />
            </View>
          </TouchableOpacity>
        }
      </View>
      <ScrollView refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}>
        {
          result?.length > 0 && result?.map(renderItem)
        }
        {
          error &&
          <EventMessage message={error?.message} style={{ marginTop: 30 }} />
        }
      </ScrollView>

      <View style={{ padding: 10, backgroundColor: '#fff' }}>
        <EventButton label={esp.lang("event/qc_idcard", "scan")} onPress={() => {
          openScanner(data?.id)
        }}
          backgroundColor={LibStyle.colorGreen} />
      </View>
      <LibSlidingup ref={dialogDetailExhibitor}>
        <View style={{ backgroundColor: '#f6f6f6', borderTopRightRadius: 20, borderTopLeftRadius: 20, paddingBottom: 35, paddingTop: 20, paddingHorizontal: 19, maxHeight: LibStyle.height - (LibStyle.height / 3) }}>
          <ScrollView>
            <View style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: LibStyle.colorGrey, flexDirection: 'row', justifyContent: 'space-between' }}>
              <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode='tail' style={{ flex: 3, fontWeight: 'bold', fontSize: 16 }}>{selectedExhibitor?.exhibitor_name}</Text>
              <Text allowFontScaling={false} style={{ flex: 1, fontWeight: 'bold', textAlign: 'right', fontSize: 16 }}>{LibUtils.number(selectedExhibitor?.qty)}</Text>
            </View>
            {
              selectedExhibitor?.detail?.length > 0 && selectedExhibitor?.detail?.map((x: any, ii: number) => {
                return (
                  <View key={ii} style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: LibStyle.colorGrey, flexDirection: 'row', justifyContent: 'space-between' }}>
                    <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode='tail' style={{ flex: 3, }}>{x.department_name}</Text>
                    <Text allowFontScaling={false} style={{ flex: 1, textAlign: 'right', }}>{LibUtils.number(x.qty)}</Text>
                  </View>
                )
              })
            }
          </ScrollView>
        </View>
      </LibSlidingup>

    </View>
  )
}