import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { Trophy, FlaskConical, ScanLine, LineChart, ArrowUpRight } from 'lucide-react';
import { leaderboardApi, experimentsApi } from '../api/client';
import { Loading } from '../components/common/Loading';
import { StatusBadge } from '../components/common/StatusBadge';
import { fmt, fmtPct } from '../lib/utils';

function SqsBar({ value, max = 80 }: { value: number | null; max?: number }) {
  if (value == null) return <span style={{ color: 'var(--text3)', fontFamily: 'var(--font-mono)', fontSize: 15 }}>—</span>;
  const pct = Math.min(100, (value / max) * 100);
  const color = value >= 70 ? 'var(--green)' : value >= 55 ? 'var(--cyan)' : value >= 40 ? 'var(--gold)' : 'var(--text3)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 600, color, width: 42, textAlign: 'right', flexShrink: 0 }}>
        {value.toFixed(1)}
      </span>
      <div style={{ flex: 1, height: 4, background: 'var(--border-md)', borderRadius: 2, minWidth: 60 }}>
        <div style={{ width: `${pct}%`, height: '100%', borderRadius: 2, background: color, transition: 'width 0.3s ease' }} />
      </div>
    </div>
  );
}

function QuickLink({ icon: Icon, label, sub, to, accent }: { icon: any; label: string; sub: string; to: string; accent: string }) {
  const navigate = useNavigate();
  return (
    <button
      onClick={() => navigate(to)}
      style={{
        background: 'var(--bg1)',
        border: '1px solid var(--border)',
        borderRadius: 12,
        padding: '20px 22px',
        textAlign: 'left',
        cursor: 'pointer',
        transition: 'all 0.15s',
        display: 'flex',
        flexDirection: 'column',
        gap: 12,
        boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
      }}
      onMouseEnter={e => {
        const el = e.currentTarget as HTMLButtonElement;
        el.style.borderColor = `color-mix(in srgb, ${accent} 40%, transparent)`;
        el.style.boxShadow = '0 4px 12px rgba(0,0,0,0.07)';
      }}
      onMouseLeave={e => {
        const el = e.currentTarget as HTMLButtonElement;
        el.style.borderColor = 'var(--border)';
        el.style.boxShadow = '0 1px 3px rgba(0,0,0,0.04)';
      }}
    >
      <div style={{
        width: 40, height: 40, borderRadius: 10,
        background: `color-mix(in srgb, ${accent} 10%, transparent)`,
        border: `1px solid color-mix(in srgb, ${accent} 20%, transparent)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon size={18} style={{ color: accent }} />
      </div>
      <div>
        <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--text1)', marginBottom: 4 }}>{label}</div>
        <div style={{ fontSize: 14, color: 'var(--text3)' }}>{sub}</div>
      </div>
    </button>
  );
}

export function DashboardPage() {
  const navigate = useNavigate();

  const { data: lb } = useQuery({
    queryKey: ['leaderboard', 'sqs', false, 10],
    queryFn: () => leaderboardApi.list({ sort_by: 'sqs', top: 10 }),
  });

  const { data: promoted } = useQuery({
    queryKey: ['experiments', '', 'promoted', ''],
    queryFn: () => experimentsApi.list({ status: 'promoted', sort_by: 'sqs', limit: 10 }),
  });

  const { data: allExp } = useQuery({
    queryKey: ['experiments', '', '', ''],
    queryFn: () => experimentsApi.list({ limit: 1 }),
  });

  const topEntry = lb?.entries[0];

  return (
    <div style={{ padding: '36px 40px' }} className="fade-up">
      {/* Header */}
      <div style={{ marginBottom: 36, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.10em', color: 'var(--text3)', textTransform: 'uppercase', marginBottom: 8 }}>
            ACE-F STRATEGY OS
          </div>
          <h1 style={{ fontSize: 34, fontWeight: 700, color: 'var(--text1)', letterSpacing: '-0.02em' }}>Overview</h1>
        </div>
        {topEntry && (
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 12, color: 'var(--text3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', marginBottom: 4 }}>#1 STRATEGY</div>
            <div
              onClick={() => navigate(`/experiments/${encodeURIComponent(topEntry.experiment_name)}`)}
              style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--cyan)', cursor: 'pointer' }}
            >
              {topEntry.experiment_name.split('_').pop()}
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 32, fontWeight: 700, color: 'var(--gold)', marginTop: 2 }}>
              {fmt(topEntry.sqs_score)}
              <span style={{ fontSize: 14, color: 'var(--text3)', fontWeight: 400, marginLeft: 6 }}>SQS</span>
            </div>
          </div>
        )}
      </div>

      {/* Stat strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 28 }}>
        {[
          { label: 'Total Strategies', value: allExp?.total, color: 'var(--text1)' },
          { label: 'On Leaderboard', value: lb?.total, color: 'var(--cyan)' },
          { label: 'Top SQS', value: fmt(topEntry?.sqs_score), color: 'var(--gold)' },
          { label: 'Top Test Return', value: fmtPct(topEntry?.total_return_pct, 0), color: topEntry && (topEntry.total_return_pct ?? 0) >= 0 ? 'var(--green)' : 'var(--red)' },
        ].map(({ label, value, color }) => (
          <div key={label} style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 12, padding: '20px 22px', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
            <div style={{ fontSize: 12, color: 'var(--text3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.07em', marginBottom: 10, textTransform: 'uppercase' }}>{label}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 32, fontWeight: 700, color }}>{value ?? '—'}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 20 }}>
        {/* Leaderboard preview */}
        <div style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
          <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--text1)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Trophy size={16} style={{ color: 'var(--gold)' }} />
              Top Strategies
            </div>
            <button onClick={() => navigate('/leaderboard')} style={{ fontSize: 13, color: 'var(--cyan)', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-mono)', display: 'flex', alignItems: 'center', gap: 4 }}>
              all <ArrowUpRight size={13} />
            </button>
          </div>
          {!lb && <Loading />}
          <div>
            {lb?.entries.slice(0, 8).map((entry, i) => (
              <div
                key={entry.entry_id}
                onClick={() => navigate(`/experiments/${encodeURIComponent(entry.experiment_name)}`)}
                style={{
                  display: 'grid',
                  gridTemplateColumns: '32px 1fr 140px',
                  alignItems: 'center',
                  gap: 12,
                  padding: '11px 22px',
                  borderBottom: i < 7 ? '1px solid var(--border)' : 'none',
                  cursor: 'pointer',
                  transition: 'background 0.1s',
                }}
                onMouseEnter={e => (e.currentTarget.style.background = 'var(--cyan-dim)')}
                onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
              >
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', textAlign: 'right' }}>
                  {entry.rank}
                </span>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--text2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {entry.experiment_name}
                </span>
                <SqsBar value={entry.sqs_score} />
              </div>
            ))}
          </div>
        </div>

        {/* Promoted */}
        <div style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
          <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--text1)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 9, height: 9, borderRadius: '50%', background: 'var(--green)' }} />
              Pinned Strategies
            </div>
            <button onClick={() => navigate('/experiments')} style={{ fontSize: 13, color: 'var(--cyan)', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-mono)', display: 'flex', alignItems: 'center', gap: 4 }}>
              all <ArrowUpRight size={13} />
            </button>
          </div>
          {!promoted && <Loading />}
          <div>
            {promoted?.experiments.length === 0 && (
              <div style={{ padding: '36px 0', textAlign: 'center', color: 'var(--text3)', fontFamily: 'var(--font-mono)', fontSize: 14 }}>
                no promoted experiments
              </div>
            )}
            {promoted?.experiments.slice(0, 8).map((exp, i) => (
              <div
                key={exp.name}
                onClick={() => navigate(`/experiments/${encodeURIComponent(exp.name)}`)}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  padding: '11px 22px',
                  borderBottom: i < Math.min((promoted.experiments.length - 1), 7) ? '1px solid var(--border)' : 'none',
                  cursor: 'pointer',
                  transition: 'background 0.1s',
                }}
                onMouseEnter={e => (e.currentTarget.style.background = 'var(--cyan-dim)')}
                onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
              >
                <StatusBadge status={exp.status} />
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--text2)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {exp.name}
                </span>
                {exp.sqs_score != null && (
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 600, color: 'var(--green)', flexShrink: 0 }}>
                    {fmt(exp.sqs_score)}
                  </span>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Quick nav */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <QuickLink icon={Trophy} label="Leaderboard" sub="SQS rankings" to="/leaderboard" accent="var(--gold)" />
        <QuickLink icon={FlaskConical} label="Strategies" sub="Browse & manage" to="/experiments" accent="var(--cyan)" />
        <QuickLink icon={ScanLine} label="Backtest" sub="Run & visualize" to="/backtest" accent="var(--orange)" />
        <QuickLink icon={LineChart} label="Paper Trading" sub="Live sessions" to="/paper" accent="var(--green)" />
      </div>
    </div>
  );
}
