import * as React from 'react';

interface TwitterEmbedProps {
  tweetId: string;
  theme?: 'light' | 'dark';
  className?: string;
  align?: 'left' | 'center' | 'right';
}

export async function TwitterEmbed({
  tweetId,
  theme = 'light',
  className = "",
  align = 'center'
}: TwitterEmbedProps) {
  let embedHtml = '';

  try {
    const oEmbedUrl = `https://publish.twitter.com/oembed?url=https://twitter.com/twitter/status/${tweetId}&theme=${theme}`;
    const response = await fetch(oEmbedUrl);

    if (response.ok) {
      const data = await response.json();
      embedHtml = data.html || '';
    } else {
      console.warn(`Twitter oEmbed failed for tweet ${tweetId}: ${response.status}`);
    }
  } catch (error) {
    console.warn(`Failed to fetch Twitter embed for ${tweetId}:`, error);
  }

  const alignmentClass = align === 'left' ? 'mr-auto ml-0' : align === 'right' ? 'ml-auto mr-0' : 'mx-auto';

  return (
    <div className={`not-prose ${className} ${alignmentClass} w-4/5`} data-theme={theme} data-align={align}>
      {embedHtml ? (
        <div dangerouslySetInnerHTML={{ __html: embedHtml }} />
      ) : (
        <div className="p-6 bg-slate-50 border border-dashed border-slate-200 rounded-lg text-center text-slate-600 text-sm flex flex-col items-center gap-2">
          <svg className="w-5 h-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M23 3a10.9 10.9 0 01-3.14 1.53 4.48 4.48 0 00-7.86 3v1A10.66 10.66 0 013 4s-4 9 5 13a11.64 11.64 0 01-7 2c9 5 20 0 20-11.5a4.5 4.5 0 00-.08-.83A7.72 7.72 0 0023 3z"/>
          </svg>
          <span>Unable to load tweet</span>
          <a href={`https://twitter.com/i/status/${tweetId}`} target="_blank" rel="noopener noreferrer" className="text-slate-600 hover:text-slate-900 font-medium text-sm">
            View on Twitter →
          </a>
        </div>
      )}
    </div>
  );
}
