import { useState, useEffect, useCallback } from 'react';

const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:3010';

const CAP_TABS = [
  { id: 'all', label: '🌐 All', color: 'text-slate-300' },
  { id: 'large', label: '🏛️ Large Cap', color: 'text-blue-400' },
  { id: 'mid', label: '🏢 Mid Cap', color: 'text-purple-400' },
  { id: 'small', label: '🔬 Small Cap', color: 'text-orange-400' },
  { id: 'etf', label: '📦 ETFs', color: 'text-green-400' },
];

function fmtMktCap(n) {
  if (n == null) return '—';
  if (n >= 1e12) return `$${(n / 1e12).toFixed(2)}T`;
  if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
  if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
  return `$${n.toFixed(0)}`;
}

function fmtVolume(n) {
  if (n == null) return '—';
  if (n >= 1e9) return `${(n / 1e9).toFixed(1)}B`;
  if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
  if (n >= 1e3) return `${(n / 1e3).toFixed(0)}K`;
  return `${n}`;
}

function ChangeBadge({ value }) {
  if (value == null) return <span className="text-slate-500">—</span>;
  const positive = value >= 0;
  return (
    <span className={`font-semibold tabular-nums ${
      positive ? 'text-emerald-400' : 'text-red-400'
    }`}>
      {positive ? '+' : ''}{value.toFixed(2)}%
    </span>
  );
}

function CapBadge({ tier }) {
  const styles = {
    LARGE: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
    MID: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
    SMALL: 'bg-orange-500/20 text-orange-400 border-orange-500/30',
    ETF: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',
    UNKNOWN: 'bg-slate-700 text-slate-400 border-slate-600',
  };
  return (
    <span className={`text-xs px-2 py-0.5 rounded border font-medium ${
      styles[tier] || styles.UNKNOWN
    }`}>
      {tier}
    </span>
  );
}

export default function MarketScreenerPanel({ onSelectSymbol }) {
  const [activeTab, setActiveTab] = useState('all');
  const [sortBy, setSortBy] = useState('market_cap');
  const [sortDir, setSortDir] = useState('desc');
  const [search, setSearch] = useState('');
  const [data, setData] = useState([]);
  const [leaderboard, setLeaderboard] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [lastUpdated, setLastUpdated] = useState(null);

  const fetchData = useCallback(async () => {
    try {
      const cap = activeTab === 'all' ? '' : activeTab;
      const url = `${API_BASE}/api/market/universe${cap ? `?cap=${cap}` : ''}`;
      const [universeRes, lbRes] = await Promise.allSettled([
        fetch(url).then(r => r.json()),
        fetch(`${API_BASE}/api/market/leaderboard`).then(r => r.json()),
      ]);

      if (universeRes.status === 'fulfilled' && universeRes.value.success) {
        setData(universeRes.value.data || []);
        setLastUpdated(new Date());
      }
      if (lbRes.status === 'fulfilled' && lbRes.value.success) {
        setLeaderboard(lbRes.value.data);
      }
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [activeTab]);

  useEffect(() => {
    setLoading(true);
    fetchData();
    const interval = setInterval(fetchData, 60000);
    return () => clearInterval(interval);
  }, [fetchData]);

  const processed = [...data]
    .filter(r => {
      if (!search) return true;
      const q = search.toUpperCase();
      return r.symbol.includes(q) || r.name.toUpperCase().includes(q) || r.sector?.toUpperCase().includes(q);
    })
    .sort((a, b) => {
      const av = a[sortBy] ?? -Infinity;
      const bv = b[sortBy] ?? -Infinity;
      return sortDir === 'desc' ? bv - av : av - bv;
    });

  const toggleSort = (col) => {
    if (sortBy === col) setSortDir(d => d === 'desc' ? 'asc' : 'desc');
    else { setSortBy(col); setSortDir('desc'); }
  };

  const SortIcon = ({ col }) => {
    if (sortBy !== col) return <span className="text-slate-600 ml-1">⇅</span>;
    return <span className="text-blue-400 ml-1">{sortDir === 'desc' ? '↓' : '↑'}</span>;
  };

  return (
    <div className="space-y-4">
      {/* Leaderboard strip */}
      {leaderboard && (
        <div className="grid grid-cols-3 gap-3">
          <LeaderCard title="🚀 Top Gainers" items={leaderboard.top_gainers} type="gain" />
          <LeaderCard title="📉 Top Losers" items={leaderboard.top_losers} type="loss" />
          <LeaderCard title="🔥 Most Active" items={leaderboard.most_active} type="volume" />
        </div>
      )}

      {/* Main screener card */}
      <div className="bg-slate-900 border border-slate-700/50 rounded-xl overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-slate-700/50">
          <div className="flex items-center gap-3">
            <h2 className="text-white font-bold text-lg">📊 Market Screener</h2>
            {lastUpdated && (
              <span className="text-xs text-slate-500">
                Updated {lastUpdated.toLocaleTimeString()}
              </span>
            )}
            {loading && <span className="text-xs text-blue-400 animate-pulse">Refreshing...</span>}
          </div>
          <div className="flex items-center gap-2">
            <input
              type="text"
              placeholder="Search symbol or name..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 w-52"
            />
            <button
              onClick={fetchData}
              className="bg-slate-800 hover:bg-slate-700 border border-slate-600 text-slate-300 px-3 py-1.5 rounded-lg text-sm transition-colors"
            >
              ↻
            </button>
          </div>
        </div>

        {/* Cap tier tabs */}
        <div className="flex border-b border-slate-700/50 bg-slate-950/30">
          {CAP_TABS.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`px-4 py-2.5 text-sm font-medium transition-all ${
                activeTab === tab.id
                  ? `border-b-2 border-blue-500 ${tab.color} bg-blue-500/5`
                  : 'text-slate-500 hover:text-slate-300'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Table */}
        {error ? (
          <div className="p-8 text-center text-red-400">
            <p>⚠️ {error}</p>
            <button onClick={fetchData} className="mt-2 text-blue-400 underline text-sm">Retry</button>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-slate-500 text-xs uppercase tracking-wide bg-slate-950/50">
                  <th className="text-left px-4 py-3 font-medium">Symbol</th>
                  <th className="text-left px-4 py-3 font-medium">Name</th>
                  <th className="text-left px-4 py-3 font-medium">Sector</th>
                  <th
                    className="text-right px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors"
                    onClick={() => toggleSort('price')}
                  >Price <SortIcon col="price" /></th>
                  <th
                    className="text-right px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors"
                    onClick={() => toggleSort('change_pct')}
                  >Change <SortIcon col="change_pct" /></th>
                  <th
                    className="text-right px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors"
                    onClick={() => toggleSort('market_cap')}
                  >Mkt Cap <SortIcon col="market_cap" /></th>
                  <th
                    className="text-right px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors"
                    onClick={() => toggleSort('volume')}
                  >Volume <SortIcon col="volume" /></th>
                  <th className="text-center px-4 py-3 font-medium">Cap Tier</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-800/50">
                {loading && data.length === 0 ? (
                  Array.from({ length: 10 }).map((_, i) => (
                    <tr key={i} className="animate-pulse">
                      {Array.from({ length: 8 }).map((_, j) => (
                        <td key={j} className="px-4 py-3">
                          <div className="h-4 bg-slate-800 rounded w-full" />
                        </td>
                      ))}
                    </tr>
                  ))
                ) : processed.length === 0 ? (
                  <tr><td colSpan={8} className="px-4 py-12 text-center text-slate-500">No results found</td></tr>
                ) : (
                  processed.map(row => (
                    <tr
                      key={row.symbol}
                      onClick={() => onSelectSymbol?.(row.symbol)}
                      className="hover:bg-slate-800/40 cursor-pointer transition-colors group"
                    >
                      <td className="px-4 py-3">
                        <span className="font-bold text-white group-hover:text-blue-400 transition-colors">
                          {row.symbol}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-slate-400 max-w-[180px] truncate">{row.name}</td>
                      <td className="px-4 py-3">
                        <span className="text-xs text-slate-500 bg-slate-800 px-2 py-0.5 rounded">
                          {row.sector}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right tabular-nums">
                        <span className="text-white font-medium">
                          {row.price != null ? `$${row.price.toFixed(2)}` : '—'}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <ChangeBadge value={row.change_pct} />
                      </td>
                      <td className="px-4 py-3 text-right text-slate-300 tabular-nums">
                        {fmtMktCap(row.market_cap)}
                      </td>
                      <td className="px-4 py-3 text-right text-slate-400 tabular-nums">
                        {fmtVolume(row.volume)}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <CapBadge tier={row.capTier} />
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}

        {/* Footer */}
        <div className="px-4 py-2 border-t border-slate-700/50 bg-slate-950/30 flex justify-between items-center">
          <span className="text-xs text-slate-600">{processed.length} of {data.length} symbols</span>
          <span className="text-xs text-slate-600">Powered by Yahoo Finance • Free data • 60s refresh</span>
        </div>
      </div>
    </div>
  );
}

function LeaderCard({ title, items = [], type }) {
  return (
    <div className="bg-slate-900 border border-slate-700/50 rounded-xl p-3">
      <div className="text-xs font-semibold text-slate-400 mb-2">{title}</div>
      <div className="space-y-1.5">
        {items.slice(0, 5).map(item => (
          <div key={item.symbol} className="flex items-center justify-between">
            <span className="text-white font-medium text-sm">{item.symbol}</span>
            {type === 'volume' ? (
              <span className="text-slate-400 text-xs tabular-nums">
                {item.volume >= 1e6 ? `${(item.volume / 1e6).toFixed(1)}M` : item.volume}
              </span>
            ) : (
              <ChangeBadge value={item.change_pct} />
            )}
          </div>
        ))}
        {items.length === 0 && <div className="text-slate-600 text-xs">Loading...</div>}
      </div>
    </div>
  );
}
