import { Box, Link, Chip, List, ListItem, ListItemText } from '@mui/material';
import { OpenInNew, Comment, TrendingUp } from '@mui/icons-material';
import GenericWidget from './GenericWidget';

function NewsWidget({ data, sx }) {
  if (!data || data.error) {
    return (
      <GenericWidget className="news-widget" title="News" sx={{ opacity: 0.5, ...sx }}>
        <p className="widget-error">
          {data?.message || 'News data unavailable'}
        </p>
      </GenericWidget>
    );
  }

  // Handle Reddit data
  if (data.type === 'reddit' && data.posts) {
    const subreddit = data.url?.match(/\/r\/([^\/\.]+)/)?.[1] || 'Reddit';

    return (
      <GenericWidget className="news-widget" title={`r/${subreddit}`} sx={{ ...sx }}>
        <List dense>
          {data.posts.slice(0, 5).map((post, index) => (
            <ListItem key={index} disablePadding sx={{ mb: 1 }}>
              <ListItemText
                primary={
                  <Box sx={{ display: 'flex', alignItems: 'start', gap: 1 }}>
                    {post.thumbnail && post.thumbnail.startsWith('http') && (
                      <Link
                        href={post.url}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Box
                          component="img"
                          src={post.thumbnail}
                          alt={post.title}
                          sx={{
                            width: 70,
                            height: 70,
                            objectFit: 'cover',
                            borderRadius: 1,
                            flexShrink: 0
                          }}
                        />
                      </Link>
                    )}
                    <Link
                      href={post.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      sx={{
                        textDecoration: 'none',
                        color: 'text.primary',
                        '&:hover': { textDecoration: 'underline' }
                      }}
                    >
                      <div className="news-title">
                        {post.title}
                        <OpenInNew sx={{ fontSize: 14 }} />
                      </div>
                    </Link>
                  </Box>
                }
                secondaryTypographyProps={{ component: 'div' }}
                secondary={
                  <Box sx={{ display: 'flex', gap: 1, mt: 0.5 }}>
                    <Chip
                      icon={<TrendingUp />}
                      label={post.score}
                      size="small"
                      variant="outlined"
                    />
                    <Chip
                      icon={<Comment />}
                      label={post.comments}
                      size="small"
                      variant="outlined"
                    />
                    <span className="news-author">by {post.author}</span>
                  </Box>
                }
              />
            </ListItem>
          ))}
        </List>
      </GenericWidget>
    );
  }

  // Handle RSS feed data
  if (data.type === 'rss' && data.items) {
    return (
      <GenericWidget title={data.feedTitle || 'RSS Feed'} sx={{ ...sx }}>
        <List dense>
          {data.items.slice(0, 5).map((item, index) => (
            <ListItem key={index} disablePadding sx={{ mb: 1 }}>
              <ListItemText
                primary={
                  <Box sx={{ display: 'flex', alignItems: 'start', gap: 1 }}>
                    {(item.thumbnail || item.enclosure?.url || item['media:thumbnail']?.url) && (
                      <Link
                        href={item.link}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Box
                          component="img"
                          src={item.thumbnail || item.enclosure?.url || item['media:thumbnail']?.url}
                          alt={item.title}
                          sx={{
                            width: 70,
                            height: 70,
                            objectFit: 'cover',
                            borderRadius: 1,
                            flexShrink: 0
                          }}
                        />
                      </Link>
                    )}
                    <Link
                      href={item.link}
                      target="_blank"
                      rel="noopener noreferrer"
                      sx={{
                        textDecoration: 'none',
                        color: 'text.primary',
                        '&:hover': { textDecoration: 'underline' }
                      }}
                    >
                      <div className="news-title">
                        {item.title}
                        <OpenInNew sx={{ fontSize: 14 }} />
                      </div>
                    </Link>
                  </Box>
                }
                secondaryTypographyProps={{ component: 'div' }}
                secondary={
                  <Box>
                    <div className="news-date">
                      {item.pubDate && new Date(item.pubDate).toLocaleDateString()}
                    </div>
                    {item.description && (
                      <div className="news-description">
                        {item.description.replace(/<[^>]*>?/gm, '')}
                      </div>
                    )}
                  </Box>
                }
              />
            </ListItem>
          ))}
        </List>
      </GenericWidget>
    );
  }

  // Handle Hacker News data
  if (data.type === 'hackernews' && data.storyIds) {
    return (
      <GenericWidget title="Hacker News" sx={{ ...sx }}>
        <p className="widget-info">
          {data.storyIds.length} top stories loaded
        </p>
        <p className="widget-caption">
          (Story details will load when API is configured)
        </p>
      </GenericWidget>
    );
  }

  // Default fallback for unknown data types
  return (
    <GenericWidget title="News" sx={{ ...sx }}>
      <p className="widget-info">
        Data format not recognized
      </p>
      <p className="widget-caption">
        {JSON.stringify(data).substring(0, 100)}...
      </p>
    </GenericWidget>
  );
}

export default NewsWidget;