import React, { useEffect, useMemo, useRef } from 'react';
import { getPageTitle } from '@/constants';
import { useCopilotArticleStream } from '@/hooks/useCopilotArticleStream';
import { processBogamark } from '@/lib/bogamarkProcessor';
import { ErrorBoundary } from './ErrorBoundary';

interface ArticleProps {
  topic: string;
  initialContent?: string;
}

function ArticleContent({ topic, initialContent }: ArticleProps) {
  const shouldStream = !initialContent || initialContent.trim() === '';
  const {
    content: streamedContent,
    error,
    shouldRedirect,
    displayTitle,
  } = useCopilotArticleStream(shouldStream ? topic : '');
  const articleRef = useRef<HTMLElement>(null);

  const processedContent = useMemo(() => {
    if (initialContent) {
      return initialContent;
    }
    if (!streamedContent) {
      return '';
    }
    return processBogamark(streamedContent);
  }, [initialContent, streamedContent]);

  useEffect(() => {
    if (!articleRef.current || !processedContent) return;

    articleRef.current.innerHTML = processedContent;
  }, [processedContent]);

  useEffect(() => {
    if (shouldRedirect) {
      if (window.sessionTracker?.skipRecordingHistory) {
        window.sessionTracker.skipRecordingHistory();
      }
      window.location.href = shouldRedirect;
    }
  }, [shouldRedirect]);

  useEffect(() => {
    if (displayTitle) {
      document.title = getPageTitle(displayTitle);
      const headerElement = document.querySelector('h1.text-3xl');
      if (headerElement) {
        headerElement.textContent = displayTitle;
      }
    }
  }, [displayTitle]);

  if (error) {
    return (
      <div className="article-error">
        <p>Failed to load article: {error}</p>
      </div>
    );
  }

  return <article ref={articleRef} className="topic-article" />;
}

export default function Article(props: ArticleProps) {
  return (
    <ErrorBoundary
      resetKeys={[props.topic]}
      resetOnPropsChange={true}
      fallback={
        <div className="error-boundary">
          <div className="error-boundary-content">
            <h3>Article Error</h3>
            <p>
              Failed to load the article content. This might be due to a network issue or invalid
              content format.
            </p>
          </div>
        </div>
      }
    >
      <ArticleContent {...props} />
    </ErrorBoundary>
  );
}
