// withHooks
import { EventTms_homeProperty } from 'esoftplay/cache/event/tms_home/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 { LibStatusbar } from 'esoftplay/cache/lib/statusbar/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect, useRef } from 'react';

import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Animated, Easing, Pressable, Text, View } from 'react-native';


export interface EventTms_out_successArgs {

}
export interface EventTms_out_successProps {

}

const dataListTicketExit = useGlobalState<any[]>([], { persistKey: 'event_exit_tiket_sync', loadOnInit: true, inFastStorage: true })
export function syncTicketExit(): useGlobalReturn<any[]> {
  return dataListTicketExit
}


export default function m(props: EventTms_out_successProps): any {
  const { scan_type, data, url, post, url_ticket_update, url_ticket_detail, price_type, gate_type, event_id, selectGate, typeScanner, event_title, configPriority }: any = LibNavigation.getArgsAll<any>(props)

  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);
  }

  useEffect(() => {
    // sementara price_id tak jupuk index 0
    EventTms_homeProperty.addCounterOutOpenGate(1, post?.price_id?.[0])
    dataListTicketExit?.get()
    createDataExit()
    animateProgressBar()
  }, [])

  function createDataExit() {
    dataListTicketExit.set(LibObject.push(dataListTicketExit.get(), [url, post])())
    EventTms_homeProperty.subscribeSyncExit().trigger(dataListTicketExit.get())
  }

  let uniquePrices: any = {};

  data?.list?.filter((entry: any) => {
    return entry.checked == 1;
  }).forEach((entry: any) => {
    uniquePrices[entry.price_name] = true;
  });

  let uniquePriceNames = Object.keys(uniquePrices);

  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: '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' }}>{uniquePriceNames.join(',')}</Text>
            <Text allowFontScaling={false} style={{ textAlign: 'center', fontSize: 26, marginTop: 20, color: LibStyle.colorRed }}>{esp.lang("event/tms_out_success", "exit")}</Text>
          </View>

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