// withHooks
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 { LibStatusbar } from 'esoftplay/cache/lib/statusbar/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { UserClass } from 'esoftplay/cache/user/class/import';
import { useRef } from 'react';

import { EventTms_homeProperty } from 'esoftplay/cache/event/tms_home/import';
import esp from 'esoftplay/esp';
import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useSafeState from 'esoftplay/state';
import { LinearGradient } from 'expo-linear-gradient';
import React, { useEffect } from 'react';
import { Animated, Easing, Pressable, Text, View } from 'react-native';


export interface EventTms_in_successArgs {

}
export interface EventTms_in_successProps {

}

export const syncUsedTiketState = useGlobalState<any[]>([], { persistKey: 'event_entrance_success_tiket_sync', loadOnInit: true, inFastStorage: true })
export function syncUsedTiket(): useGlobalReturn<any[]> {
  return syncUsedTiketState
}

export default function m(props: EventTms_in_successProps): any {
  const { scan_type, url_ticket_update, url_ticket_detail, price_type, selectedTicket, gate_type, qr_code, event_id, selectGate, typeScanner, event_title, qty, configPriority } = LibNavigation.getArgsAll<any>(props)
  // const { set } = EventFirebase_socket()
  const [isPaused, setIsPaused] = useSafeState<boolean>(false)
  const progress = useRef(new Animated.Value(0)).current;
  const animation = useRef<Animated.CompositeAnimation | null>(null);
  const [pausedValue, setPausedValue] = useSafeState(0);

  function animateProgressBar() {
    const duration = 1000; // Ubah durasi animasi sesuai kebutuhan Anda

    if (!isPaused) {
      animation.current = Animated.timing(progress, {
        toValue: 1,
        duration: duration - duration * pausedValue,
        easing: Easing.linear,
        useNativeDriver: false,
      });

      animation.current.start(({ finished }) => {
        if (finished) {
          setIsPaused(false);
          setPausedValue(0);

          // script next nya disini
          LibNavigation.replace('component/scanner', {
            selectGate: selectGate,
            fromPage: 'event/tms_home',
            event_id: event_id,
            event_title: event_title,
            typeScanner: typeScanner,
            gate_type: gate_type,
            price_type: price_type,
            url_ticket_detail: url_ticket_detail,
            url_ticket_update: url_ticket_update,
            configPriority: configPriority,
            scan_type: scan_type
          })
        }
      });
    } else {
      if (animation.current) {
        animation.current.stop(); // Hentikan animasi
        animation.current = null;
      }
      setPausedValue(progress._value);
    }

    setIsPaused(!isPaused);
  }

  let _qty = qty ? qty : 1

  useEffect(() => {
    entrance()
    animateProgressBar()
  }, [])


  function entrance() {
    useTicket()
  }

  function useTicket() {
    let url = url_ticket_update

    let post = {
      "target-url": `https://api.${esp.config().domain}/gate_checkin`,
      price_id: selectedTicket?.price_id,
      qr: encodeURIComponent(qr_code),
      trx_id: new Date().getTime() + "" + UserClass.state().get()?.id,
      event_id: event_id,
      gate_id: selectGate?.id,
      is_tms: 1,
      qty: _qty,
      tms_id: UserClass.state().get()?.id,
      scanned: LibUtils.moment().format('YYYY-MM-DD HH:mm:ss'),
    }
    EventTms_homeProperty.addCounterEntranceOpenGate(1, selectedTicket?.price_id)
    syncUsedTiketState.set(LibObject.push(syncUsedTiketState.get(), [url, post])())
    EventTms_homeProperty.subscribeSync().trigger(syncUsedTiketState.get())
  }

  const widthInterpolate = progress.interpolate({
    inputRange: [0, 1],
    outputRange: ['0%', '100%'],
  });

  return (
    <View style={{ flex: 1 }}>
      <LibStatusbar style='light' />
      <Pressable
        onPressIn={animateProgressBar}
        onPressOut={animateProgressBar}
        style={{ backgroundColor: '#000', height: LibStyle.height }}>
        <LibPicture source={{ uri: selectedTicket && selectedTicket?.user_image != "" ? decodeURIComponent(selectedTicket?.user_image) : 'https://www.w3schools.com/howto/img_avatar.png' }} style={{ width: LibStyle.width, height: LibStyle.height - (LibStyle.height / 4) }} resizeMode={"cover"} />

        <View style={{ marginTop: LibStyle.STATUSBAR_HEIGHT + 5, alignSelf: 'center', height: 5, width: LibStyle.width - 20, backgroundColor: 'rgba(255,255,255,0.3)', borderRadius: 10, position: 'absolute', top: 5, }}>
          <Animated.View style={{ width: widthInterpolate, height: 5, backgroundColor: LibStyle.colorPrimary, borderRadius: 10, }} />
        </View>

        <LinearGradient
          // Background Linear Gradient
          style={{
            height: LibStyle.height - (LibStyle.height / 3),
            width: LibStyle.width,
            position: 'absolute',
            left: 0,
            right: 0,
            bottom: 0,
          }}
          colors={['rgba(255,255,255,0)', 'rgba(0,0,0,0.55)', 'rgba(0,0,0,1)', 'rgba(0,0,0,1)']}>
          <View style={{ flex: 1, padding: 15, justifyContent: 'flex-end', paddingBottom: 100, alignContent: 'center', alignItems: 'center' }}>
            <Text allowFontScaling={false} style={{ textAlign: 'center', flexWrap: 'wrap', fontSize: 35, letterSpacing: 2, fontWeight: '900', color: '#fff' }}>{selectedTicket?.title?.split("+").join(' ')}</Text>
            <Text allowFontScaling={false} style={{ textAlign: 'center', fontSize: 14, marginTop: 20, color: '#fff' }}>{gate_type == "1" ? esp.lang("event/tms_in_success", "in") : esp.lang("event/tms_in_success", "out")}</Text>
          </View>

        </LinearGradient>
      </Pressable>
    </View>
  )
}