'use client';

import React, { createContext, useContext, useEffect, useState } from 'react';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { apiClient } from '@/lib/apiClient';

interface GoogleConfig {
  clientId: string;
  enabled: boolean;
  loading: boolean;
}

const GoogleConfigContext = createContext<GoogleConfig>({
  clientId: '',
  enabled: false,
  loading: true,
});

export function useGoogleConfig() {
  return useContext(GoogleConfigContext);
}

export function ClientGoogleProvider({ children }: { children: React.ReactNode }) {
  const [config, setConfig] = useState<GoogleConfig>({
    clientId: '',
    enabled: false,
    loading: true,
  });

  useEffect(() => {
    let active = true;
    apiClient
      .get<{ data: { google_client_id: string; google_auth_enabled: boolean } }>('/api/v1/auth/config')
      .then((res) => {
        if (!active) return;
        setConfig({
          clientId: res.data.google_client_id,
          enabled: res.data.google_auth_enabled && !!res.data.google_client_id,
          loading: false,
        });
      })
      .catch((err) => {
        console.error('Failed to load Google client configuration:', err);
        if (!active) return;
        setConfig({
          clientId: '',
          enabled: false,
          loading: false,
        });
      });
    return () => {
      active = false;
    };
  }, []);

  if (config.loading) {
    return (
      <GoogleConfigContext.Provider value={config}>
        {children}
      </GoogleConfigContext.Provider>
    );
  }

  if (config.enabled && config.clientId) {
    return (
      <GoogleConfigContext.Provider value={config}>
        <GoogleOAuthProvider clientId={config.clientId}>
          {children}
        </GoogleOAuthProvider>
      </GoogleConfigContext.Provider>
    );
  }

  return (
    <GoogleConfigContext.Provider value={config}>
      {children}
    </GoogleConfigContext.Provider>
  );
}
