import { useState, useEffect } from 'react';
import { ArrowRight } from 'lucide-react';
import { useAppContext } from '../../context/AppContext';
import { fetchNews, type NewsArticle as MarketNewsArticle } from '../../lib/marketApi';
import { SkeletonBlock, SkeletonText } from '../Skeleton';
import { Button } from '../ui/Primitives';

// ─── Portfolio Summary ────────────────────────────────────────────────────────

function PortfolioSummary() {
  const { botState } = useAppContext();
  const positions = botState.positions ?? [];
  const account   = botState.accountSnapshot;

  const totalValue = account
    ? account.cash + positions.reduce((s, p) => s + (p.marketValue ?? 0), 0)
    : positions.reduce((s, p) => s + (p.marketValue ?? 0), 0);

  const totalPnl  = positions.reduce((s, p) => s + (p.unrealizedPnl ?? 0), 0);
  const pnlPos    = totalPnl >= 0;

  const fmt$ = (n: number) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(n);

  return (
    <div className="right-panel-section">
      {/* Header */}
      <div className="right-panel-header">
        <span>Portfolio</span>
        <Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
          View All <ArrowRight size={12} />
        </Button>
      </div>

      {/* Total value */}
      <div className="right-panel-metric">
        <div className="right-panel-metric-value">
          {fmt$(totalValue)}
        </div>
        <div className="right-panel-metric-change" data-positive={pnlPos ? 'true' : 'false'}>
          {pnlPos ? '+' : ''}{fmt$(totalPnl)} unrealized
        </div>
      </div>

      {/* Column headers */}
      <div className="right-panel-table-head">
        {['Symbol','Price','Change','Value'].map(h => (
          <span key={h}>
            {h}
          </span>
        ))}
      </div>

      {/* Rows */}
      {positions.length === 0 ? (
        <div className="right-panel-empty">
          <div>No open positions</div>
          <p>
            Filled Trade Plans and manual entries will appear here.
          </p>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {positions.slice(0, 6).map(pos => {
            const pct = pos.unrealizedPnlPercent ?? 0;
            const pos_ = pct >= 0;
            return (
              <div key={pos.id} className="right-panel-table-row">
                <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--foreground)' }}>{pos.symbol}</span>
                <span style={{ fontSize: 12, color: 'var(--foreground)' }}>{pos.currentPrice?.toFixed(2) ?? '—'}</span>
                <span style={{ fontSize: 12, fontWeight: 600, color: pos_ ? 'var(--bl-success)' : 'var(--bl-danger)' }}>
                  {pos_ ? '+' : ''}{pct.toFixed(2)}%
                </span>
                <span style={{ fontSize: 12, color: 'var(--foreground)' }}>{fmt$(pos.marketValue ?? 0)}</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── News Feed ────────────────────────────────────────────────────────────────

type NewsArticle = MarketNewsArticle;

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const m = Math.floor(diff / 60_000);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

function NewsCard({ article }: { article: NewsArticle }) {
  const img = article.images?.[0]?.url;
  return (
    <a
      href={article.url}
      target="_blank"
      rel="noopener noreferrer"
      className="right-panel-news-card"
    >
      {img && (
        <img
          src={img} alt=""
          style={{ width: 52, height: 44, objectFit: 'cover', borderRadius: 6, flexShrink: 0 }}
          onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
        />
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 12, fontWeight: 600, color: 'var(--foreground)',
          lineHeight: 1.4,
          display: '-webkit-box',
          WebkitLineClamp: 2,
          WebkitBoxOrient: 'vertical',
          overflow: 'hidden',
          marginBottom: 4,
        }}>
          {article.headline}
        </div>
        <div style={{ fontSize: 10, color: 'var(--muted-foreground)' }}>
          {article.source} · {timeAgo(article.created_at)}
        </div>
      </div>
    </a>
  );
}

function NewsFeedSkeleton() {
  return (
    <div role="status" aria-label="Loading news" style={{ padding: '4px 0 8px' }}>
      {[0, 1, 2].map((i) => (
        <div
          key={i}
          style={{
            display: 'flex',
            gap: 10,
            padding: '10px 16px',
            borderBottom: i < 2 ? '1px solid var(--border)' : 'none',
          }}
        >
          <SkeletonBlock width={48} height={48} radius={10} style={{ flexShrink: 0 }} />
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 7, paddingTop: 3 }}>
            <SkeletonText width="92%" />
            <SkeletonText width="68%" />
            <SkeletonText width="36%" />
          </div>
        </div>
      ))}
    </div>
  );
}

function NewsFeed() {
  const { activeSymbol } = useAppContext();
  const [news, setNews]       = useState<NewsArticle[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError]     = useState<string | null>(null);

  useEffect(() => {
    if (!activeSymbol) { setNews([]); return; }
    let cancelled = false;
    setLoading(true);
    setError(null);
    // Use the authenticated marketApi helper so the request carries the
    // platform Bearer token; the raw `fetch()` we used before was hitting
    // requireAuth and 401-ing on every render.
    fetchNews(activeSymbol, 8)
      .then(list => { if (!cancelled) setNews(list); })
      .catch(err  => { if (!cancelled) setError(err?.message ?? 'Failed to load news'); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [activeSymbol]);

  return (
    <div>
      <div className="right-panel-header right-panel-news-header">
        <span>Latest News</span>
        <Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
          View All <ArrowRight size={12} />
        </Button>
      </div>

      {loading && <NewsFeedSkeleton />}

      {!loading && error && (
        <div className="right-panel-error">{error}</div>
      )}

      {!loading && !error && news.length === 0 && (
        <div className="right-panel-empty mx-4 mb-4 mt-2">
          <div>
            {activeSymbol ? `No news for ${activeSymbol}` : 'No symbol selected'}
          </div>
          <p>
            {activeSymbol ? 'Try another ticker or check back after the next market update.' : 'Search a ticker to load market news.'}
          </p>
        </div>
      )}

      {!loading && news.map((a, i) => <NewsCard key={a.id ?? a.url ?? i} article={a} />)}
    </div>
  );
}

// ─── Right Panel container ────────────────────────────────────────────────────

export function RightPanel() {
  return (
    <aside className="dashboard-right-panel right-panel">
      <div className="right-panel-block">
        <PortfolioSummary />
      </div>
      <NewsFeed />
    </aside>
  );
}
