'use client';

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

interface ResponsiveIframeProps {
  src: string;
  className?: string;
  allow?: string;
  style?: React.CSSProperties;
}

export function ResponsiveIframe({ src, className = '', allow, style }: ResponsiveIframeProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const { data: session } = useSession();
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [iframeSrc, setIframeSrc] = useState<string>('');
  const [hasTriedRefresh, setHasTriedRefresh] = useState(false);

  // Refresh NextAuth session (which will also refresh Keycloak tokens) before loading iframe
  useEffect(() => {
    // If no src, nothing to do
    if (!src) {
      return;
    }

    // Check if user just logged out - prevent refresh if logout is in progress
    const justLoggedOut = sessionStorage.getItem('just_logged_out') === 'true';
    const logoutCookie = document.cookie.split(';').some(c => c.trim().startsWith('logout_in_progress=true'));
    
    if (justLoggedOut || logoutCookie) {
      console.warn('Logout in progress, redirecting to sign-in instead of refreshing session');
      window.location.href = '/signin';
      return;
    }

    // If no session yet, wait for it (don't set src yet)
    if (!session) {
      return;
    }

    // If already tried refresh for this src, just set it
    if (hasTriedRefresh) {
      if (!iframeSrc) {
        setIframeSrc(src);
      }
      return;
    }

    // Ensure session has required tokens before proceeding
    if (!session.accessToken || !session.refreshToken) {
      console.warn('Session missing required tokens, redirecting to sign-in');
      window.location.href = '/signin';
      return;
    }

    const refreshSession = async () => {
      setIsRefreshing(true);
      setHasTriedRefresh(true);
      
      try {
        // Wait a bit to ensure NextAuth session is fully established
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // Double-check logout flag before making the request
        const stillLoggedOut = sessionStorage.getItem('just_logged_out') === 'true';
        if (stillLoggedOut) {
          console.warn('Logout detected during refresh, aborting');
          window.location.href = '/signin';
          return;
        }
        
        // Call our API to refresh the Keycloak session
        // This ensures tokens are fresh and may help refresh Keycloak session cookies
        const response = await fetch('/api/auth/refresh-keycloak-session', {
          method: 'GET',
          credentials: 'include', // Include cookies
        });
        
        if (response.ok) {
          console.log('Session refreshed before loading iframe');
          setIframeSrc(src);
        } else {
          const errorData = await response.json().catch(() => ({}));
          
          // If session was invalidated, redirect to sign-in
          if (response.status === 401 && errorData.error === 'SessionInvalidated') {
            console.warn('Keycloak session invalidated, redirecting to sign-in');
            window.location.href = '/signin';
            return;
          }
          
          console.warn('Failed to refresh session, loading iframe anyway (may require login)');
          // Still load iframe, but it may prompt for login
          setIframeSrc(src);
        }
      } catch (error) {
        console.error('Error refreshing session:', error);
        // On error, still try to load iframe
        setIframeSrc(src);
      } finally {
        setIsRefreshing(false);
      }
    };

    refreshSession();
  }, [session, src, hasTriedRefresh, iframeSrc]);

  // Listen for logout messages from iframe applications
  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      // Security: Only accept messages from known iframe origins
      // In production, you should validate event.origin against your iframe URLs
      
      // Check if message is a logout request from iframe
      if (event.data && typeof event.data === 'object') {
        if (event.data.type === 'KEYCLOAK_LOGOUT' || event.data.type === 'LOGOUT') {
          console.log('Received logout request from iframe, triggering dashboard logout');
          
          // Mark logout in progress
          sessionStorage.setItem('just_logged_out', 'true');
          document.cookie = 'logout_in_progress=true; path=/; max-age=60';
          
          // Trigger dashboard logout
          if (session?.idToken) {
            const keycloakIssuer = process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER;
            if (keycloakIssuer) {
              const keycloakLogoutUrl = new URL(
                `${keycloakIssuer}/protocol/openid-connect/logout`
              );
              keycloakLogoutUrl.searchParams.append(
                'post_logout_redirect_uri',
                window.location.origin + '/signin?logout=true'
              );
              keycloakLogoutUrl.searchParams.append(
                'id_token_hint',
                session.idToken
              );
              window.location.replace(keycloakLogoutUrl.toString());
            }
          } else {
            // Fallback: redirect to signin
            window.location.replace('/signin?logout=true');
          }
        }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, [session]);

  useEffect(() => {
    const iframe = iframeRef.current;
    if (!iframe || !iframeSrc) return;

    const calculateHeight = () => {
      const pageY = (elem: HTMLElement): number => {
        return elem.offsetParent ? 
          (elem.offsetTop + pageY(elem.offsetParent as HTMLElement)) : 
          elem.offsetTop;
      };

      const height = document.documentElement.clientHeight;
      const iframeY = pageY(iframe);
      const newHeight = Math.max(0, height - iframeY);
      iframe.style.height = `${newHeight}px`;
    };

    const handleHashChange = () => {
      if (window.location.hash && window.location.hash.length && iframe.src) {
        const iframeURL = new URL(iframe.src);
        iframeURL.hash = window.location.hash;
        iframe.src = iframeURL.toString();
      }
    };

    // Initial setup
    calculateHeight();
    handleHashChange();

    // Event listeners
    window.addEventListener('resize', calculateHeight);
    window.addEventListener('hashchange', handleHashChange);
    iframe.addEventListener('load', calculateHeight);

    // Cleanup
    return () => {
      window.removeEventListener('resize', calculateHeight);
      window.removeEventListener('hashchange', handleHashChange);
      iframe.removeEventListener('load', calculateHeight);
    };
  }, [iframeSrc]);

  return (
    <>
      {isRefreshing && (
        <div className="flex items-center justify-center w-full h-full absolute bg-black/50 z-10">
          <div className="text-center bg-white p-4 rounded-lg">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto mb-4"></div>
            <p className="text-gray-600">Actualisation de la session...</p>
          </div>
        </div>
      )}
      
      <iframe
        ref={iframeRef}
        id="myFrame"
        src={iframeSrc || src}
        className={`w-full border-none ${className}`}
        style={{
          display: 'block',
          width: '100%',
          height: '100%',
          ...style
        }}
        allow={allow}
        allowFullScreen
      />
    </>
  );
} 