import { ModalLoading } from '@/components/modal/ModalLoading';
import { getSageBuilderHtmlContent, sageBuilderError, sageBuilderStatus } from '@/store/features/sage-builder/selectors';
import { getSageBuilderDashboard } from '@/store/features/sage-builder/thunk';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import React, { useEffect, useRef } from 'react';

const SageBuilderPage = () => {
  const dispatch = useAppDispatch();
  const iframeRef = useRef<HTMLIFrameElement>(null);
  
  const htmlContent = useAppSelector(getSageBuilderHtmlContent);
  const status = useAppSelector(sageBuilderStatus);
  const error = useAppSelector(sageBuilderError);

  useEffect(() => {
    // Charger le dashboard au montage du composant
    if (status === 'idle') {
      dispatch(getSageBuilderDashboard());
    }
  }, [dispatch, status]);

  useEffect(() => {
    // Injecter le HTML dans l'iframe quand il est disponible
    if (htmlContent && iframeRef.current && status === 'succeeded') {
      const iframeDoc = iframeRef.current.contentDocument || iframeRef.current.contentWindow?.document;
      if (iframeDoc) {
        iframeDoc.open();
        iframeDoc.write(htmlContent);
        iframeDoc.close();
      }
    }
  }, [htmlContent, status]);

  const handleRetry = () => {
    dispatch(getSageBuilderDashboard());
  };

  return (
    <div className="h-screen w-full overflow-hidden bg-gray-50 relative">
      {/* Loading Overlay */}
      {status === 'loading' && <ModalLoading />}

      {/* Error State */}
      {status === 'failed' && error && (
        <div className="absolute inset-0 z-50 flex items-center justify-center bg-gray-50">
          <div className="text-center max-w-md px-4">
            <div className="inline-flex items-center justify-center w-16 h-16 mb-4 bg-red-100 rounded-full">
              <svg 
                className="w-8 h-8 text-red-600" 
                fill="none" 
                viewBox="0 0 24 24" 
                stroke="currentColor"
              >
                <path 
                  strokeLinecap="round" 
                  strokeLinejoin="round" 
                  strokeWidth={2} 
                  d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" 
                />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              Erreur de chargement
            </h3>
            <p className="text-sm text-gray-600 mb-4">
              {error}
            </p>
            <button
              onClick={handleRetry}
              className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
            >
              Réessayer
            </button>
          </div>
        </div>
      )}

      {/* Iframe */}
      <iframe
        ref={iframeRef}
        className={`w-full h-full border-0 transition-opacity duration-300 ${
          status === 'succeeded' ? 'opacity-100' : 'opacity-0'
        }`}
        title="Sage Builder Dashboard"
        sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
      />
    </div>
  );
};

export default SageBuilderPage;