import * as React from 'react';
import {View, Colors} from 'react-native-ui-lib';
import TopBar from '../../components/molecules/TopBar';
import ScreenView from '../../components/atoms/ScreenView';
import Button from '../../components/atoms/Button';
import {Dimensions, DimensionValue, TouchableOpacity} from 'react-native';
import {
RouteProp,
useFocusEffect,
useNavigation,
useRoute,
} from '@react-navigation/native';
import {useUserStore} from '../../stores';
import purchaseService from '../../services/purchaseService';
import {HomeStackParamList} from '../../navigation/stacks/HomeStack';
import MaskedView from '@react-native-masked-view/masked-view';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {
useSharedValue,
withRepeat,
withTiming,
Easing,
// useAnimatedStyle,
} from 'react-native-reanimated';
import {Audio} from 'expo-av';
import {Sound} from 'expo-av/build/Audio';
import {BarCodeScanningResult, CameraView, FlashMode, useCameraPermissions} from 'expo-camera';
import Toast from 'react-native-toast-message';
import handleErrors from '../../utils/handleErrors';
import {
// $animatedLine,
$camera,
$maskElement,
$maskedContainer,
$transparentSquareBorder,
} from './_styles';
import {
Footer,
InstructionOverlay,
Loading,
MaskedElement,
NfcInfo,
} from './_components';
import {OpenByNfcKeyResponse} from '../../services/purchase';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
const CAMERA_ASPECT_RATIO = [16, 9] as const;
const {width: containerWidth, height: containerHeight} =
Dimensions.get('window');
const NfcCouponCameraScreen = () => {
const navigate = useNavigation<NativeStackNavigationProp<any>>();
// #region Routes and Navigation
const route: RouteProp<
{params: HomeStackParamList['NfcCouponCamera']},
'params'
> = useRoute();
const benefitType = route.params.benefitType;
// #region States
const user = useUserStore(state => state.user);
const [sound, setSound] = React.useState<Sound | null>(null);
const [isFlashOn, setIsFlashOn] = React.useState(false);
const [refreshing, setRefreshing] = React.useState(false);
const [nfcInfo, setNfcInfo] = React.useState<OpenByNfcKeyResponse | null>(
null,
);
const [isScanning, setIsScanning] = React.useState(true);
// #region Permissions
const [permission, requestPermission] = useCameraPermissions();
// #region Animations
const linePosition = useSharedValue(-130);
// const animatedStyle = useAnimatedStyle(() => ({
// transform: [{translateY: linePosition.value}],
// }));
const soundRef = React.useRef<Audio.Sound | null>(null); // Avoid stale state issues
const [cameraWidth, cameraHeight] = React.useMemo<
[DimensionValue, DimensionValue]
>(() => {
const width = Math.round(
containerHeight / (CAMERA_ASPECT_RATIO[0] / CAMERA_ASPECT_RATIO[1]),
);
const height = Math.round(
containerWidth * (CAMERA_ASPECT_RATIO[0] / CAMERA_ASPECT_RATIO[1]),
);
return [Math.min(width, containerWidth), Math.min(height, containerHeight)];
}, []);
const toggleCameraFlash = () => {
setIsFlashOn(!isFlashOn);
};
const handleBarCodeScanned = async ({data}: BarCodeScanningResult) => {
if (!isScanning) {
return;
}
setIsScanning(false);
sound?.replayAsync();
setRefreshing(true);
const response = await purchaseService.openByNfcKey({
customerId: user?.id || 0,
benefitType,
link: data,
});
if (response.ok && response.data) {
setNfcInfo(response.data);
} else {
if (Array.isArray(response.data) && response.data[0]?.message) {
handleErrors(response.data);
} else {
Toast.show({
type: 'genericError',
text1: 'Não encontramos benefícios para este cupom!',
});
}
}
setRefreshing(false);
setTimeout(() => {
setIsScanning(true);
}, 4000);
};
const handleNewScan = () => {
setNfcInfo(null);
};
useFocusEffect(
React.useCallback(() => {
const loadSound = async () => {
const {sound: newSound} = await Audio.Sound.createAsync(
require('../../assets/sounds/beep.mp3'),
);
setSound(newSound);
soundRef.current = newSound;
};
const startAnimations = () => {
linePosition.value = withRepeat(
withTiming(130, {
duration: 1000,
easing: Easing.inOut(Easing.ease),
}),
-1,
true,
);
};
loadSound();
startAnimations();
return () => {
if (soundRef.current) {
soundRef.current.unloadAsync();
}
};
}, [linePosition]),
);
React.useEffect(() => {
if (!permission) {
requestPermission();
}
}, [permission, requestPermission]);
const closeScreen = () => {
navigate.pop(2);
};
if (!permission?.granted) {
return (
<ScreenView bgColor="#000000">
<View flex center>
<Button label="Permitir acesso à câmera" onPress={requestPermission} />
</View>
</ScreenView>
);
}
return (
<ScreenView bgColor="#000000">
<View bg-dmBlack flex>
<TopBar
hideBackButton
leftElement={
<TouchableOpacity
onPress={closeScreen}
marginR-s3
hitSlop={{top: 10, bottom: 10, left: 10, right: 10}}>
<Icon name={'close'} size={30} color={Colors.black} />
</TouchableOpacity>
}
title="Escanear Cupom Fiscal"
rightElement={
<TouchableOpacity
onPress={toggleCameraFlash}
marginR-s3
hitSlop={{top: 10, bottom: 10, left: 10, right: 10}}>
<Icon
name={isFlashOn ? 'flash-off' : 'flash'}
size={30}
color={Colors.black}
/>
</TouchableOpacity>
}
/>
{refreshing && <Loading />}
{!refreshing && (
<MaskedView style={$maskedContainer} maskElement={<MaskedElement />}>
<View style={$maskElement} />
<CameraView
onBarcodeScanned={isScanning ? handleBarCodeScanned : undefined} // Fixed prop name
barcodeScannerSettings={{
barcodeTypes: ['qr'],
}}
flash={isFlashOn ? FlashMode.on : FlashMode.off}
facing="back"
mode="picture"
style={[
$camera,
{
width: cameraWidth,
height: cameraHeight,
},
]}
/>
{/* <Animated.View style={[$animatedLine, animatedStyle]} /> */}
<View style={$transparentSquareBorder} />
</MaskedView>
)}
{!refreshing && <InstructionOverlay />}
{!refreshing && nfcInfo && (
<Footer>
<NfcInfo
cnpj={nfcInfo.cnpj}
empresa={nfcInfo.empresa}
endereco={nfcInfo.endereco}
valorTotalPago={nfcInfo.valorTotalPago}
/>
<Button
label="Escanear novo cupom"
iconName="qrcode-scan"
onPress={handleNewScan}
/>
</Footer>
)}
</View>
</ScreenView>
);
};
export default NfcCouponCameraScreen;