import AsyncStorage from '@react-native-async-storage/async-storage';
import AppText from 'components/AppText';
import React, { useEffect, useState } from 'react';
import { Alert, StyleSheet, TouchableOpacity, View } from 'react-native';
import ReactNativeBiometrics from 'react-native-biometrics';
import GesturePassword from 'react-native-gesture-password';

const LOCK_ENABLED = 'LOCK_ENABLED';
const LOCK_TYPE = 'LOCK_TYPE';
const LOCK_PASSWORD = 'LOCK_PASSWORD';
const LOCK_PATTERN = 'LOCK_PATTERN';
const LOCK_BIOMETRIC = 'LOCK_BIOMETRIC';

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

const LockScreen = ({ onAuthenticated }: Props) => {
  const [enabled, setEnabled] = useState(false);
  const [lockType, setLockType] = useState<'pin' | 'password' | 'pattern'>(
    'pin',
  );
  const [password, setPassword] = useState('');
  const [pattern, setPattern] = useState('');
  const [biometricAvailable, setBiometricAvailable] = useState(false);

  useEffect(() => {
    const load = async () => {
      const lockEnabled = await AsyncStorage.getItem(LOCK_ENABLED);
      if (lockEnabled === 'true') {
        const type = await AsyncStorage.getItem(LOCK_TYPE);
        const pass = await AsyncStorage.getItem(LOCK_PASSWORD);
        const pat = await AsyncStorage.getItem(LOCK_PATTERN);
        setLockType(type as any);
        setPassword(pass || '');
        setPattern(pat || '');
        setEnabled(true);

        const bioEnabled = await AsyncStorage.getItem(LOCK_BIOMETRIC);
        if (bioEnabled === 'true') {
          const rnBiometrics = new ReactNativeBiometrics();
          const { available } = await rnBiometrics.isSensorAvailable();
          if (available) {
            setBiometricAvailable(true);
            try {
              const { success } = await rnBiometrics.simplePrompt({
                promptMessage: 'Unlock with biometrics',
              });
              if (success) onAuthenticated();
            } catch (e) {}
          }
        }
      }
    };
    load();
  }, [onAuthenticated]);

  if (!enabled) return null;

  const handlePatternEnd = async (inputPattern: string) => {
    if (!pattern) {
      // pattern birinchi marta saqlanmoqda
      await AsyncStorage.setItem(LOCK_PATTERN, inputPattern);
      setPattern(inputPattern);
      Alert.alert('OK', 'Pattern saqlandi');
    } else {
      if (inputPattern === pattern) {
        onAuthenticated();
      } else {
        Alert.alert('Xato', 'Pattern noto‘g‘ri');
      }
    }
  };

  const handleUnlockPasswordOrPin = (input: string) => {
    if (input === password) {
      onAuthenticated();
    } else {
      Alert.alert('Xato', 'Parol noto‘g‘ri');
    }
  };

  return (
    <View style={styles.container}>
      <AppText style={styles.title}>Unlock</AppText>

      {lockType === 'pattern' ? (
        <GesturePassword
          style={{ flex: 1 }}
          onEnd={handlePatternEnd}
          interval={300}
        />
      ) : (
        <View style={{ marginTop: 50 }}>
          <TouchableOpacity
            style={styles.button}
            onPress={() => handleUnlockPasswordOrPin(password)}
          >
            <AppText style={styles.buttonText}>
              Unlock with {lockType.toUpperCase()}
            </AppText>
          </TouchableOpacity>
        </View>
      )}

      {biometricAvailable && (
        <TouchableOpacity
          style={[styles.button, { marginTop: 10, backgroundColor: '#4CAF50' }]}
          onPress={async () => {
            const rnBiometrics = new ReactNativeBiometrics();
            try {
              const { success } = await rnBiometrics.simplePrompt({
                promptMessage: 'Unlock with biometrics',
              });
              if (success) onAuthenticated();
            } catch (e) {}
          }}
        >
          <AppText style={styles.buttonText}>Unlock with Biometrics</AppText>
        </TouchableOpacity>
      )}
    </View>
  );
};

export default LockScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
    backgroundColor: '#fff',
  },
  title: { fontSize: 24, textAlign: 'center', marginBottom: 20 },
  button: {
    backgroundColor: '#28A7E8',
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
  },
  buttonText: { color: '#fff', fontSize: 18, fontWeight: 'bold' },
});
