import { startRegistration, startAuthentication } from '@simplewebauthn/browser';
import api from '../lib/api-client';
import { useEffect, useState } from 'react';

export function useBiometrics() {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [platformAvailable, setPlatformAvailable] = useState<boolean | null>(null);

    const [supportError, setSupportError] = useState<string | null>(
        typeof window === 'undefined' ? 'Biometric authentication is not available.' : null
    );

    useEffect(() => {
        let cancelled = false;

        const checkSupport = () => {
            if (typeof window === 'undefined') return;

            // Warning: WebAuthn usually requires HTTPS, but we allow the attempt here 
            // in case the app is running in a context the browser considers secure (like localhost or some APKs).
            if (!window.isSecureContext) {
                console.warn('Biometrics: Running in a non-secure context (HTTP). The browser may block this.');
            }

            let errorMsg: string | null = null;

            // Check for WebAuthn API support
            if (!('credentials' in navigator) || !('create' in navigator.credentials)) {
                errorMsg = 'Your browser does not support WebAuthn biometrics. Please try Chrome, Edge, or Safari.';
            }
            // Check for PublicKeyCredential
            else if (!('PublicKeyCredential' in window)) {
                errorMsg = 'WebAuthn is not supported in this browser.';
            }

            if (!cancelled) {
                // Only set error if we found one, otherwise wait for platform check
                if (errorMsg) {
                    setSupportError(errorMsg);
                    setPlatformAvailable(false);
                }
            }
        };

        checkSupport();

        const checkPlatform = async () => {
            try {
                if (typeof window === 'undefined') return;
                
                // If we already found a basic support error, stop
                if (!('PublicKeyCredential' in window)) return;

                const fn = (window.PublicKeyCredential as any)
                    ?.isUserVerifyingPlatformAuthenticatorAvailable;
                
                if (typeof fn !== 'function') {
                    // Not all browsers implement this probe; treat as unknown (null)
                    if (!cancelled) setPlatformAvailable(null);
                    return;
                }

                const ok = await fn.call(window.PublicKeyCredential);
                if (!cancelled) {
                    setPlatformAvailable(Boolean(ok));
                    if (ok === false) {
                        setSupportError('This device/browser does not have a supported biometric/passkey authenticator available.');
                    }
                }
            } catch {
                if (!cancelled) setPlatformAvailable(false);
            }
        };

        checkPlatform();

        return () => {
            cancelled = true;
        };
    }, []);

    const isSupported = supportError === null;

    const registerBiometric = async () => {
        setLoading(true);
        setError(null);
        try {
            if (supportError) {
                setError(supportError);
                return false;
            }

            // 1. Get Challenge
            const resp = await api.post('/auth/biometric/register/challenge');
            const options = resp.data;

            // 2. Create Credential
            const attResp = await startRegistration(options);

            // 3. Verify
            await api.post('/auth/biometric/register/verify', attResp);
            
            return true;
        } catch (err: any) {
            console.error(err);
            const msg = err.response?.data?.error || err.message || 'Registration failed';
            setError(msg);
            return false;
        } finally {
            setLoading(false);
        }
    };

    const loginBiometric = async (email?: string) => {
        setLoading(true);
        setError(null);
        try {
            if (supportError) {
                setError(supportError);
                return null;
            }

            // 1. Get Challenge
            const resp = await api.post('/auth/biometric/login/challenge', { email });
            const options = resp.data;

            // 2. Get Credential
            const asseResp = await startAuthentication(options);

            // 3. Verify
            const verifyResp = await api.post('/auth/biometric/login/verify', asseResp);
            
            return verifyResp.data; // { success: true, token: '...', user: ... }
        } catch (err: any) {
            console.error(err);
            const msg = err.response?.data?.error || err.message || 'Authentication failed';

            // If a browser throws a generic WebAuthn error, provide actionable guidance.
            if (typeof msg === 'string' && msg.toLowerCase().includes('webauthn')) {
                setError('Biometric login is unavailable here. Use Chrome/Safari on HTTPS (or install the PWA).');
            } else {
                setError(msg);
            }
            return null;
        } finally {
            setLoading(false);
        }
    };

    return {
        registerBiometric,
        loginBiometric,
        loading,
        error,
        isSupported,
        supportError,
    };
}

