'use client';

import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';

export function RocketChatAuth() {
  const { data: session } = useSession();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function authenticateWithRocketChat() {
      if (!session?.user?.email) {
        setError('No user session available');
        return;
      }

      try {
        console.log('Authenticating with Rocket.Chat for user:', session.user.email);
        
        // Call our API to get Rocket.Chat tokens
        const response = await fetch('/api/auth/rocket-login');
        
        // Get the text response for debugging if there's an error
        const responseText = await response.text();
        
        if (!response.ok) {
          console.error('Failed to authenticate with Rocket.Chat:', responseText);
          setError(`Failed to authenticate: ${response.status} ${response.statusText}`);
          return;
        }
        
        // Parse the JSON now that we've read the text
        const data = JSON.parse(responseText);
        
        if (data.rocketChatToken && data.rocketChatUserId) {
          console.log('Received tokens from API:', {
            hasToken: !!data.rocketChatToken,
            hasUserId: !!data.rocketChatUserId
          });
          
          // Get the current hostname to set domain cookies properly
          const hostname = window.location.hostname;
          const domain = hostname.includes('localhost') ? 'localhost' : hostname;
          
          console.log(`Setting cookies for domain: ${domain}`);
          
          // Store tokens in cookies that can be accessed by the Rocket.Chat iframe
          document.cookie = `rc_token=${data.rocketChatToken}; path=/; domain=${domain}; SameSite=None; Secure`;
          document.cookie = `rc_uid=${data.rocketChatUserId}; path=/; domain=${domain}; SameSite=None; Secure`;
          
          // Also store in localStorage which Rocket.Chat might check
          localStorage.setItem('Meteor.loginToken', data.rocketChatToken);
          localStorage.setItem('Meteor.userId', data.rocketChatUserId);
          
          console.log('Successfully authenticated with Rocket.Chat');
          setIsAuthenticated(true);
          setError(null);
        } else {
          setError('Received invalid response from authentication API');
          console.error('Invalid response data:', data);
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        console.error('Error authenticating with Rocket.Chat:', errorMessage);
        setError(`Error: ${errorMessage}`);
      }
    }
    
    authenticateWithRocketChat();
  }, [session]);

  // This component doesn't render visible UI by default
  return error ? (
    <div className="fixed bottom-4 right-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded z-50" role="alert">
      <strong className="font-bold">Authentication Error: </strong>
      <span className="block sm:inline">{error}</span>
    </div>
  ) : null;
}

export default RocketChatAuth; 