import React, { useRef, useEffect, useState, useCallback } from 'react';
import { cn } from '@/lib/utils';
import { createIframeContent } from '@/utils/code';

export function CustomCode({ code = '<p>Example HTML</p> ', sectionId }: { code?: string; sectionId?: string }) {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [iframeHeight, setIframeHeight] = useState(200);
  const [key, setKey] = useState(0);

  useEffect(() => {
    setKey((prev) => prev + 1);
  }, [code]);

  const updateIframeContent = useCallback(() => {
    if (!iframeRef.current) return;

    try {
      const iframe = iframeRef.current;
      const doc = iframe.contentDocument || iframe.contentWindow?.document;
      if (!doc) return;

      doc.open();
      doc.write(createIframeContent(code));
      doc.close();
    } catch (error) {
      console.error('Error updating iframe content:', error);
    }
  }, [code]);

  useEffect(() => {
    updateIframeContent();
  }, [updateIframeContent, key]);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data?.type === 'resize' && typeof event.data.height === 'number') {
        setIframeHeight(event.data.height);
      }
    };

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

  return (
    <div className={cn('custom-code-component w-full h-full border-none max-w-[1366px] mx-auto')} id={sectionId}>
      <iframe
        key={key}
        ref={iframeRef}
        sandbox='allow-same-origin allow-scripts allow-popups'
        className='w-full rounded-md'
        style={{
          height: `${iframeHeight}px`,
          transition: 'height 0.2s ease',
          overflow: 'hidden',
        }}
        title='Custom HTML Preview'
      />
    </div>
  );
}
