import { useCallback } from 'react';
import * as LocalAuthentication from 'expo-local-authentication';
import { useSettingsStore } from '@/store/settingsStore';

export function useBiometricAuth() {
  const { isBiometricEnabled } = useSettingsStore();

  const authenticate = useCallback(async (): Promise<boolean> => {
    if (!isBiometricEnabled) return true;

    try {
      const isAvailable = await LocalAuthentication.hasHardwareAsync();
      if (!isAvailable) return true;

      const isEnrolled = await LocalAuthentication.isEnrolledAsync();
      if (!isEnrolled) return true;

      const result = await LocalAuthentication.authenticateAsync({
        promptMessage: 'Authenticate with biometrics',
        fallbackLabel: 'Use passcode',
        cancelLabel: 'Cancel',
      });

      return result.success;
    } catch {
      return false;
    }
  }, [isBiometricEnabled]);

  const enableBiometric = useCallback(async (): Promise<boolean> => {
    const isAvailable = await LocalAuthentication.hasHardwareAsync();
    const isEnrolled = await LocalAuthentication.isEnrolledAsync();

    if (!isAvailable || !isEnrolled) return false;

    const result = await LocalAuthentication.authenticateAsync({
      promptMessage: 'Enable biometric authentication',
      fallbackLabel: 'Use passcode',
    });

    if (result.success) {
      useSettingsStore.getState().toggleBiometric(true);
    }

    return result.success;
  }, []);

  const disableBiometric = useCallback(() => {
    useSettingsStore.getState().toggleBiometric(false);
  }, []);

  return { authenticate, enableBiometric, disableBiometric, isBiometricEnabled };
}
