import React, { useEffect, useState } from 'react';
import { Alert, StyleSheet, View, AppState } from 'react-native';
import { Text, Button } from 'react-native-paper';
import {
  Camera,
  useCameraDevice,
  useCameraPermission,
  useCodeScanner,
} from 'react-native-vision-camera';

import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';

import { StackParamsList } from '../types';

const QRScanner = () => {
  const navigation =
    useNavigation<NativeStackNavigationProp<StackParamsList>>();

  const { hasPermission, requestPermission } = useCameraPermission();

  const [isActive, setIsActive] = useState(AppState.currentState === 'active');
  const device = useCameraDevice('back');
  const [isScanning, setScanning] = useState(true);
  const codeScanner = useCodeScanner({
    codeTypes: ['qr'],
    onCodeScanned: codes => {
      if (isScanning) {
        codes.forEach(code => {
          if (code.value) {
            Alert.alert(`Scanned: ${code.value}`, undefined, [
              {
                text: 'OK',
                onPress: () => {
                  navigation.navigate('Laconic');
                },
              },
            ]);

            setScanning(false);
          }
        });
      }
    },
  });

  useEffect(() => {
    const handleAppStateChange = (newState: string) => {
      setIsActive(newState === 'active');
    };

    AppState.addEventListener('change', handleAppStateChange);

    if (!hasPermission) {
      requestPermission();
    }
  }, [hasPermission, isActive, requestPermission]);

  if (!hasPermission) {
    return (
      <View style={styles.container}>
        <Text>No Camera Permission!</Text>
        <Button onPress={() => requestPermission()}>Request Permission</Button>
      </View>
    );
  }

  if (!device) {
    return (
      <View style={styles.container}>
        <Text>No Camera Selected!</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {isActive ? (
        <Camera
          style={styles.camera}
          device={device}
          isActive={isActive}
          codeScanner={codeScanner}
          video={false}
        />
      ) : (
        <Text>No Camera Selected!</Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  camera: {
    width: 400,
    height: 500,
    borderRadius: 50,
    overflow: 'hidden',
  },
});

export default QRScanner;
