'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import Keycloak from 'keycloak-js';
import keycloak from '../lib/keycloak';

interface KeycloakContextType {
  keycloak: Keycloak | null;
  authenticated: boolean;
  loading: boolean;
  token: string | null;
  login: () => void;
  logout: () => void;
  updateToken: () => Promise<boolean>;
}

const KeycloakContext = createContext<KeycloakContextType | undefined>(undefined);

export const useKeycloak = () => {
  const context = useContext(KeycloakContext);
  if (!context) {
    throw new Error('useKeycloak must be used within a KeycloakProvider');
  }
  return context;
};

interface KeycloakProviderProps {
  children: ReactNode;
}

export const KeycloakProvider: React.FC<KeycloakProviderProps> = ({ children }) => {
  const [authenticated, setAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const [token, setToken] = useState<string | null>(null);

  useEffect(() => {
    const initKeycloak = async () => {
      try {
        console.log('🔐 Initializing Keycloak...');

        const authenticated = await keycloak.init({
          onLoad: 'check-sso',
          silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html',
          pkceMethod: 'S256',
          checkLoginIframe: false, // Désactivé pour éviter les problèmes CORS
          flow: 'standard', // Force authorization_code flow (pas implicit/hybrid)
          responseMode: 'query', // Force query string au lieu de fragment
        });

        console.log(`✅ Keycloak initialized. Authenticated: ${authenticated}`);

        setAuthenticated(authenticated);
        setToken(keycloak.token || null);

        // Rafraîchir le token automatiquement
        if (authenticated) {
          setInterval(() => {
            keycloak.updateToken(70).then((refreshed) => {
              if (refreshed) {
                console.log('🔄 Token refreshed');
                setToken(keycloak.token || null);
              }
            }).catch(() => {
              console.error('❌ Failed to refresh token');
              setAuthenticated(false);
            });
          }, 60000); // Toutes les 60 secondes
        }
      } catch (error) {
        console.error('❌ Keycloak initialization failed:', error);
      } finally {
        setLoading(false);
      }
    };

    initKeycloak();
  }, []);

  const login = () => {
    keycloak.login({
      redirectUri: window.location.origin + '/dashboard',
    });
  };

  const logout = () => {
    keycloak.logout({
      redirectUri: window.location.origin,
    });
  };

  const updateToken = async (): Promise<boolean> => {
    try {
      const refreshed = await keycloak.updateToken(30);
      if (refreshed) {
        setToken(keycloak.token || null);
      }
      return refreshed;
    } catch (error) {
      console.error('Failed to update token', error);
      return false;
    }
  };

  const value: KeycloakContextType = {
    keycloak,
    authenticated,
    loading,
    token,
    login,
    logout,
    updateToken,
  };

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