import React, {useContext, useEffect} from "react";
import {AlertContext} from "@/context/AlertContext";
import {configs} from "@/lib/configs";
import {useTranslations} from "@/lib/i18n";
import {LangContext, LangContextProps} from "@/context/LangContext";
import * as tauri from '@/lib/tauri';
import {apiPostPublic} from "@/lib/api/client";
const FacebookIcon = () => (
);
const GoogleIcon = () => (
);
const AppleIcon = () => (
);
export default function SocialForm() {
const {errorMessage} = useContext(AlertContext);
const t = useTranslations();
const {lang} = useContext(LangContext)
useEffect((): void => {
const params = new URLSearchParams(window.location.search);
const provider: string | null = params.get('provider');
if (!provider) return;
const code: string | null = params.get('code');
if (!code) return;
if (provider === 'google') {
handleGoogleLogin(code).then();
return;
}
if (provider === 'facebook') {
const state: string | null = params.get('state');
if (!state) return;
handleFacebookLogin(code, state).then();
return;
}
if (provider === 'apple') {
const state: string | null = params.get('state');
if (!state) return;
handleAppleLogin(code, state).then();
return;
}
}, []);
async function handleLoginSuccess(token: string): Promise {
await tauri.setToken(token);
await tauri.loginSuccess();
}
async function handleFacebookLogin(code: string, state: string): Promise {
if (code && state) {
const response: string = await apiPostPublic(`auth/facebook`, {
code: code,
state: state,
}, lang);
if (!response) {
errorMessage(t('socialForm.error.connection'));
return;
}
await handleLoginSuccess(response);
}
}
async function handleGoogleLogin(code: string): Promise {
if (code) {
const response: string = await apiPostPublic(`auth/google`, {
code: code,
}, lang);
if (!response) {
errorMessage(t('socialForm.error.connection'));
return;
}
await handleLoginSuccess(response);
}
}
async function handleAppleLogin(code: string, state: string): Promise {
if (code && state) {
const response: string = await apiPostPublic(`auth/apple`, {
code: code,
state: state,
}, lang);
if (!response) {
errorMessage(t('socialForm.error.connection'));
return;
}
await handleLoginSuccess(response);
}
}
async function handleOAuthClick(provider: 'google' | 'facebook' | 'apple'): Promise {
try {
const oauthUrl = `${configs.baseUrl}auth/${provider}/desktop`;
await tauri.openExternal(oauthUrl);
} catch {
errorMessage(t('socialForm.error.connection'));
}
}
return (
)
}