/**
 * useBiometrics Hook
 *
 * Hook for managing biometric authentication
 */

import { useEffect, useCallback, useState } from 'react';
import {
  useBiometricStore,
  biometricService,
  getBiometricTypeName,
  BiometricCapabilities,
  BiometricType,
} from '@/services/biometrics';

interface UseBiometricsResult {
  // Capabilities
  isAvailable: boolean;
  isEnrolled: boolean;
  biometricType: BiometricType;
  biometricTypeName: string;
  capabilities: BiometricCapabilities | null;

  // Settings
  isEnabled: boolean;
  lastUsedAt: number | null;

  // Status
  isLoading: boolean;
  isAuthenticating: boolean;
  error: string | null;

  // Actions
  checkCapabilities: () => Promise<BiometricCapabilities>;
  authenticate: (promptMessage?: string) => Promise<boolean>;
  enableBiometricLogin: (authToken: string) => Promise<boolean>;
  disableBiometricLogin: () => Promise<boolean>;
  loginWithBiometrics: () => Promise<{ success: boolean; token?: string; error?: string }>;
  isBiometricLoginAvailable: () => Promise<boolean>;
}

export function useBiometrics(): UseBiometricsResult {
  const { settings, capabilities, setCapabilities } = useBiometricStore();

  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticating, setIsAuthenticating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Check capabilities on mount
  useEffect(() => {
    setIsLoading(true);
    biometricService
      .checkCapabilities()
      .then((caps) => {
        setCapabilities(caps);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, [setCapabilities]);

  // Check capabilities
  const checkCapabilities = useCallback(async (): Promise<BiometricCapabilities> => {
    setIsLoading(true);
    setError(null);
    try {
      const caps = await biometricService.checkCapabilities();
      return caps;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Error checking capabilities';
      setError(errorMsg);
      throw err;
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Authenticate
  const authenticate = useCallback(async (promptMessage?: string): Promise<boolean> => {
    setIsAuthenticating(true);
    setError(null);

    try {
      const result = await biometricService.authenticate({
        promptMessage: promptMessage || 'Verificar identidad',
      });

      if (!result.success && result.error) {
        setError(result.error);
      }

      return result.success;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Authentication error';
      setError(errorMsg);
      return false;
    } finally {
      setIsAuthenticating(false);
    }
  }, []);

  // Enable biometric login
  const enableBiometricLogin = useCallback(async (authToken: string): Promise<boolean> => {
    setIsLoading(true);
    setError(null);

    try {
      // First verify the user can authenticate
      const authResult = await biometricService.authenticate({
        promptMessage: 'Configurar inicio de sesión biométrico',
      });

      if (!authResult.success) {
        setError(authResult.error || 'No se pudo verificar la identidad');
        return false;
      }

      // Enable biometric login
      const result = await biometricService.enableBiometricLogin(authToken);

      if (!result) {
        setError('Error al configurar el inicio de sesión biométrico');
      }

      return result;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Error enabling biometrics';
      setError(errorMsg);
      return false;
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Disable biometric login
  const disableBiometricLogin = useCallback(async (): Promise<boolean> => {
    setIsLoading(true);
    setError(null);

    try {
      const result = await biometricService.disableBiometricLogin();

      if (!result) {
        setError('Error al desactivar el inicio de sesión biométrico');
      }

      return result;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Error disabling biometrics';
      setError(errorMsg);
      return false;
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Login with biometrics
  const loginWithBiometrics = useCallback(async () => {
    setIsAuthenticating(true);
    setError(null);

    try {
      const result = await biometricService.loginWithBiometrics({
        promptMessage: 'Inicia sesión con biometría',
      });

      if (!result.success && result.error) {
        setError(result.error);
      }

      return result;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Login error';
      setError(errorMsg);
      return { success: false, error: errorMsg };
    } finally {
      setIsAuthenticating(false);
    }
  }, []);

  // Check if biometric login is available
  const isBiometricLoginAvailable = useCallback(async (): Promise<boolean> => {
    return biometricService.isBiometricLoginAvailable();
  }, []);

  // Derived values
  const isAvailable = capabilities?.isAvailable ?? false;
  const isEnrolled = capabilities?.isEnrolled ?? false;
  const biometricType = capabilities?.primaryType ?? 'none';
  const biometricTypeName = getBiometricTypeName(biometricType);

  return {
    // Capabilities
    isAvailable,
    isEnrolled,
    biometricType,
    biometricTypeName,
    capabilities,

    // Settings
    isEnabled: settings.enabled,
    lastUsedAt: settings.lastUsedAt,

    // Status
    isLoading,
    isAuthenticating,
    error,

    // Actions
    checkCapabilities,
    authenticate,
    enableBiometricLogin,
    disableBiometricLogin,
    loginWithBiometrics,
    isBiometricLoginAvailable,
  };
}
