'use client'

import { useState, useEffect } from 'react'
import type { TrumpPost } from '@/types'
import { getPosts } from '@/lib/api'
import PostRow, { SignalPill, SourceIcon, fmtPct, timeAgo } from '@/components/dashboard/PostCards'

function PostDetail({ post, onClose }: { post: TrumpPost; onClose: () => void }) {
  return (
    <div className="card" style={{ padding: 24, position: 'sticky', top: 84 }}>
      <div className="row between" style={{ marginBottom: 16 }}>
        <span className="tiny">Signal detail</span>
        <button className="icon-btn" onClick={onClose} style={{ width: 28, height: 28 }}>
          <svg width="12" height="12" viewBox="0 0 24 24"><path d="M18 6L6 18M6 6l12 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
        </button>
      </div>
      <div className="row gap-s" style={{ marginBottom: 14 }}>
        <SourceIcon source={post.source} />
        <div>
          <div style={{ fontSize: 13, fontWeight: 500 }} className="mono">@realDonaldTrump</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{new Date(post.published_at).toLocaleString()}</div>
        </div>
      </div>
      <p style={{ fontSize: 15, lineHeight: 1.55, margin: '0 0 20px' }}>{post.text}</p>

      <div className="row gap-s" style={{ marginBottom: 20 }}>
        <SignalPill signal={post.signal} />
        <span className={`chip ${post.sentiment === 'bullish' ? 'up' : post.sentiment === 'bearish' ? 'down' : 'neutral'}`}>{post.sentiment}</span>
      </div>

      <div className="tiny" style={{ marginBottom: 8 }}>AI reasoning</div>
      <div style={{ padding: 14, background: 'var(--bg-sunk)', borderRadius: 10, border: '1px solid var(--line)', fontSize: 13, lineHeight: 1.55, color: 'var(--ink-2)', marginBottom: 20 }}>
        {post.ai_reasoning || 'No reasoning available.'}
      </div>

      <div className="row between" style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 6 }}>
        <span>AI confidence</span>
        <span className="mono" style={{ color: 'var(--ink)', fontWeight: 500 }}>{post.ai_confidence}%</span>
      </div>
      <div className="confidence-bar"><div style={{ width: post.ai_confidence + '%' }} /></div>

      {post.price_impact && (
        <div style={{ marginTop: 24 }}>
          <div className="tiny" style={{ marginBottom: 10 }}>Actual price impact · {post.price_impact.asset}</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
            {(['m5', 'm15', 'm1h'] as const).map(k => {
              const v = post.price_impact![k]
              const correct = post.price_impact!['correct_' + k as 'correct_m5' | 'correct_m15' | 'correct_m1h']
              const label = k === 'm5' ? '5m' : k === 'm15' ? '15m' : '1h'
              return (
                <div key={k} style={{ padding: 12, background: 'var(--bg-sunk)', borderRadius: 10, border: '1px solid var(--line)' }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 4 }}>{label}</div>
                  <div className={`delta ${(v ?? 0) >= 0 ? 'up' : 'down'}`} style={{ fontSize: 15 }}>{fmtPct(v)}</div>
                  {correct != null && (
                    <div style={{ fontSize: 11, color: correct ? 'var(--up)' : 'var(--down)', marginTop: 4 }}>
                      {correct ? '✓ correct' : '✗ missed'}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}

export default function PostsPage() {
  const [posts, setPosts] = useState<TrumpPost[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState('all')
  const [selected, setSelected] = useState<number | null>(null)

  useEffect(() => {
    getPosts(200, 1).then(setPosts).catch(() => {}).finally(() => setLoading(false))
  }, [])

  const filtered = posts.filter(p => {
    if (filter !== 'all' && p.sentiment !== filter) return false
    return true
  })

  const counts = {
    all: posts.length,
    bullish: posts.filter(p => p.sentiment === 'bullish').length,
    bearish: posts.filter(p => p.sentiment === 'bearish').length,
    neutral: posts.filter(p => p.sentiment === 'neutral').length,
  }

  const selectedPost = posts.find(p => p.id === selected)

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Signals feed</h1>
          <p className="page-sub">Every post we tracked, every prediction we made. {posts.length} posts in the last 30 days.</p>
        </div>
        <span className="chip"><span className="live-dot" />Streaming</span>
      </div>

      <div className="row between" style={{ marginBottom: 18 }}>
        <div className="nav-tabs" style={{ background: 'var(--bg-sunk)' }}>
          {(['all', 'bullish', 'bearish', 'neutral'] as const).map(f => (
            <button key={f} className={`nav-tab ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>
              {f.charAt(0).toUpperCase() + f.slice(1)} <span style={{ color: 'var(--ink-4)', marginLeft: 4 }}>{counts[f]}</span>
            </button>
          ))}
        </div>
      </div>

      {loading && <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)' }}>Loading…</div>}

      <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 420px' : '1fr', gap: 24, alignItems: 'start' }}>
        <div className="post-stream">
          {filtered.map(p => (
            <PostRow key={p.id} post={p} selected={selected === p.id} onClick={() => setSelected(selected === p.id ? null : p.id)} />
          ))}
        </div>
        {selected && selectedPost && <PostDetail post={selectedPost} onClose={() => setSelected(null)} />}
      </div>
    </div>
  )
}
