import React, { useEffect } from 'react';
import { View, Text, Alert, StyleSheet, Platform } from 'react-native';
import ReactNativeBiometrics, { BiometryTypes } from 'react-native-biometrics';

const rnBiometrics = new ReactNativeBiometrics({
  allowDeviceCredentials: true, // PIN / Pattern fallback
});

type Props = {
  onUnlock: () => void;
};

const LockScreen: React.FC<Props> = ({ onUnlock }) => {
  useEffect(() => {
    checkAndAuthenticate();
  }, []);

  const checkAndAuthenticate = async () => {
    try {
      const { available, biometryType } =
        await rnBiometrics.isSensorAvailable();
      // const isSensorAvailable = await rnBiometrics.isSensorAvailable();
      // console.log('===============>', isSensorAvailable);
      if (!available) {
        Alert.alert(
          'Biometric not available',
          'Your device does not support biometric authentication.',
        );
        return;
      }

      console.log('Biometry Type:', biometryType);

      // Face ID / Face Unlock / Fingerprint handled by OS
      authenticate();
    } catch (error) {
      Alert.alert('Error', 'Failed to check biometric availability');
    }
  };

  const authenticate = async () => {
    try {
      const { success } = await rnBiometrics.simplePrompt({
        promptMessage: 'Unlock App',
        cancelButtonText: 'Cancel',
      });

      if (success) {
        onUnlock();
      } else {
        showRetryAlert();
      }
    } catch (error) {
      showRetryAlert();
    }
  };

  const showRetryAlert = () => {
    Alert.alert(
      'Authentication Failed',
      'Unable to authenticate using Face ID / Biometrics.',
      [
        { text: 'Retry', onPress: authenticate },
        { text: 'Cancel', style: 'cancel' },
      ],
    );
  };

  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        Authenticating using Face ID / Biometrics...
      </Text>
    </View>
  );
};

export default LockScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 16,
  },
});
