import * as React from 'react';
import { authApi, type AdminAuthUser } from '../services/api';
import { getAuthToken, setAuthToken } from '@/lib/apiClient';

interface AdminAuthContextValue {
    user: AdminAuthUser | null;
    loading: boolean;
    requestOtp: (mobile: string) => Promise<void>;
    resendOtp: (mobile: string) => Promise<void>;
    verifyOtp: (mobile: string, otp: string) => Promise<void>;
    logout: () => Promise<void>;
}

const AdminAuthContext = React.createContext<AdminAuthContextValue | null>(
    null,
);

/**
 * Provides the current admin user across the admin panel. Reads the persisted
 * token on mount and calls /auth/me to hydrate the session; on failure it
 * clears the token so ProtectedRoute redirects to login.
 */
export function AdminAuthProvider({ children }: { children: React.ReactNode }) {
    const [user, setUser] = React.useState<AdminAuthUser | null>(null);
    const [loading, setLoading] = React.useState(true);

    React.useEffect(() => {
        let cancelled = false;
        async function hydrate() {
            if (!getAuthToken()) {
                setLoading(false);
                return;
            }
            try {
                const { user } = await authApi.me();
                if (!cancelled) setUser(user);
            } catch {
                setAuthToken(null);
            } finally {
                if (!cancelled) setLoading(false);
            }
        }
        void hydrate();
        return () => {
            cancelled = true;
        };
    }, []);

    const requestOtp = React.useCallback(async (mobile: string) => {
        await authApi.requestOtp({ mobile });
    }, []);

    const resendOtp = React.useCallback(async (mobile: string) => {
        await authApi.resendOtp({ mobile });
    }, []);

    const verifyOtp = React.useCallback(async (mobile: string, otp: string) => {
        const { user } = await authApi.verifyOtp({ mobile, otp });
        setUser(user);
    }, []);

    const logout = React.useCallback(async () => {
        await authApi.logout();
        setUser(null);
    }, []);

    return (
        <AdminAuthContext.Provider
            value={{ user, loading, requestOtp, resendOtp, verifyOtp, logout }}
        >
            {children}
        </AdminAuthContext.Provider>
    );
}

export function useAdminAuth() {
    const ctx = React.useContext(AdminAuthContext);
    if (!ctx)
        throw new Error('useAdminAuth must be used within AdminAuthProvider');
    return ctx;
}
