import {
	createContext,
	useCallback,
	useContext,
	useEffect,
	useMemo,
	useState,
	type ReactNode,
} from "react";
import * as settingsApi from "../api/settings";
import type { AvatarSettings } from "../types/events";

interface AvatarContextValue extends AvatarSettings {
	loaded: boolean;
	refreshAvatars: () => Promise<void>;
	updateAvatars: (next: AvatarSettings) => void;
}

const AvatarContext = createContext<AvatarContextValue | null>(null);

export function AvatarProvider({ children }: { children: ReactNode }) {
	const [userAvatarUrl, setUserAvatarUrl] = useState("");
	const [agentAvatarUrl, setAgentAvatarUrl] = useState("");
	const [loaded, setLoaded] = useState(false);

	const refreshAvatars = useCallback(async () => {
		try {
			const data = await settingsApi.fetchAvatars();
			setUserAvatarUrl(data.userAvatarUrl || "");
			setAgentAvatarUrl(data.agentAvatarUrl || "");
		} catch {
			/* ignore */
		} finally {
			setLoaded(true);
		}
	}, []);

	const updateAvatars = useCallback((next: AvatarSettings) => {
		setUserAvatarUrl(next.userAvatarUrl || "");
		setAgentAvatarUrl(next.agentAvatarUrl || "");
		setLoaded(true);
	}, []);

	useEffect(() => {
		void refreshAvatars();
	}, [refreshAvatars]);

	const value = useMemo(
		(): AvatarContextValue => ({
			userAvatarUrl,
			agentAvatarUrl,
			loaded,
			refreshAvatars,
			updateAvatars,
		}),
		[userAvatarUrl, agentAvatarUrl, loaded, refreshAvatars, updateAvatars],
	);

	return <AvatarContext.Provider value={value}>{children}</AvatarContext.Provider>;
}

export function useAvatars(): AvatarContextValue {
	const ctx = useContext(AvatarContext);
	if (!ctx) throw new Error("useAvatars must be used within AvatarProvider");
	return ctx;
}
