import { useEffect, useState } from 'react';
import { api } from '../../api/client';
import NeonCard from '../NeonCard/NeonCard';
import type { Agent, FleetAlert, PoolStatus, AIActivityEntry } from '../../types';
import type { FleetHealth, ContributionBar, SubnetGroup, PlatformCount } from '../../help/fleetAnalytics';
import { timeToPayout } from '../../help/fleetAnalytics';
import { formatHashrate } from '../../help/fleetFilters';
import './FleetPanels.css';

export function AlertBanner({ alerts }: { alerts: FleetAlert[] }) {
  if (alerts.length === 0) return null;
  return (
    <div className="alert-banner-stack">
      {alerts.slice(0, 5).map((a) => (
        <div key={a.id} className={`alert-banner alert-${a.level}`}>
          <span className="alert-type font-tech">{a.type.replace(/_/g, ' ').toUpperCase()}</span>
          <span className="alert-msg">{a.message}</span>
          <span className="alert-time font-tech">
            {a.timestamp ? new Date(a.timestamp).toLocaleTimeString() : ''}
          </span>
        </div>
      ))}
    </div>
  );
}

export function PoolStatusPanel({ pools }: { pools: PoolStatus[] }) {
  return (
    <NeonCard accent="green" className="section" hud>
      <h2 className="section-title font-display">
        <span className="section-ornament">◆</span> Pool Stratum Status
        <span className="section-line" />
      </h2>
      {pools.length === 0 ? (
        <p className="form-hint">No forged pool connections yet — agents connect upstream on auth.</p>
      ) : (
        <div className="pool-status-grid">
          {pools.map((p) => (
            <div key={p.key} className={`pool-status-item status-${p.status}`}>
              <span className={`stratum-dot ${p.status}`} title={p.connected ? 'Connected' : 'Disconnected'} />
              <div className="pool-status-meta">
                <strong>{p.host}:{p.port}</strong>
                <span className="mono-sm">{p.use_tls ? 'TLS' : 'TCP'} · {p.wallet}…</span>
              </div>
              <span className={`pool-status-label font-tech ${p.status}`}>
                {p.status === 'green' ? 'LIVE' : p.status === 'yellow' ? 'DEGRADED' : 'DOWN'}
              </span>
            </div>
          ))}
        </div>
      )}
    </NeonCard>
  );
}

export function AIActivityPanel({ entries, agentNames }: { entries: AIActivityEntry[]; agentNames: Record<string, string> }) {
  return (
    <NeonCard accent="purple" className="section" hud>
      <h2 className="section-title font-display">
        <span className="section-ornament">◆</span> AI Activity Monitor
        <span className="section-line" />
      </h2>
      {entries.length === 0 ? (
        <p className="form-hint">No Ollama decide cycles yet — enable AI on a forged miner with Ollama running on this PC.</p>
      ) : (
        <div className="ai-activity-list">
          {entries.map((e) => (
            <div key={e.agent_id} className="ai-activity-row">
              <div>
                <strong>{agentNames[e.agent_id] || e.agent_id.slice(0, 8)}</strong>
                <span className="mono-sm"> · {e.last_tool || e.last_action || 'idle'}</span>
              </div>
              <div className="ai-activity-detail">
                <span>Decide: {e.last_decide_at ? new Date(e.last_decide_at).toLocaleTimeString() : '—'}</span>
                <span>Tools: {e.tool_call_count ?? 0}</span>
                <span className={e.last_success ? 'ok' : 'bad'}>
                  {e.last_report_at ? new Date(e.last_report_at).toLocaleTimeString() : '—'}
                </span>
              </div>
              {e.last_reasoning && <p className="ai-reasoning">{e.last_reasoning}</p>}
            </div>
          ))}
        </div>
      )}
    </NeonCard>
  );
}

interface EarningsData {
  xmr_per_day?: number;
  note?: string;
  source?: string;           // "pool_api" | "estimate"
  pending_xmr?: number;      // from pool API
  paid_xmr?: number;
  pool_hashrate?: number;
  last_payment_xmr?: number;
  last_payment_time?: string;
}

export function EarningsEstimator({ hashrate, xmrPrice }: { hashrate: number; xmrPrice?: number | null }) {
  const [data, setData] = useState<EarningsData | null>(null);

  useEffect(() => {
    if (hashrate <= 0) { setData(null); return; }
    const controller = new AbortController();
    api.getEarningsEstimate(hashrate).then((r: EarningsData) => {
      if (!controller.signal.aborted) setData(r);
    }).catch((err: unknown) => { if (!controller.signal.aborted) console.error(err); });
    return () => controller.abort();
  }, [hashrate]);

  if (!data || hashrate <= 0) return null;

  const isReal = data.source === 'pool_api';
  const usdPerDay = data.xmr_per_day != null && xmrPrice ? data.xmr_per_day * xmrPrice : null;
  const usdPending = data.pending_xmr != null && xmrPrice ? data.pending_xmr * xmrPrice : null;
  const daysLeft = timeToPayout(data.pending_xmr, data.xmr_per_day);

  return (
    <NeonCard accent="amber" className="stat-card-wrap earnings-estimator">
      <div className="stat-label font-tech">
        {isReal ? '⛏ Pool Earnings (Live)' : 'Earnings Estimate'}
      </div>
      {data.xmr_per_day != null && (
        <div className="stat-value neon-glow-amber">
          {isReal ? '' : '~'}{data.xmr_per_day.toFixed(6)} XMR/day
        </div>
      )}
      {usdPerDay != null && (
        <div className="earnings-usd-day">≈ ${usdPerDay.toFixed(2)}/day</div>
      )}
      {isReal ? (
        <div className="earnings-real-grid">
          {data.pending_xmr != null && (
            <span className="er-row">
              <span className="er-lbl">Pending</span>
              <span className="er-val">
                {data.pending_xmr.toFixed(8)} XMR
                {usdPending != null && <span className="er-usd"> (${usdPending.toFixed(2)})</span>}
              </span>
            </span>
          )}
          {daysLeft != null && (
            <span className="er-row">
              <span className="er-lbl">Payout In</span>
              <span className="er-val er-highlight">
                {daysLeft < 1 ? `${(daysLeft * 24).toFixed(1)} hrs` : `${daysLeft.toFixed(1)} days`}
              </span>
            </span>
          )}
          {data.paid_xmr != null && (
            <span className="er-row"><span className="er-lbl">Total Paid</span><span className="er-val">{data.paid_xmr.toFixed(4)} XMR</span></span>
          )}
          {data.last_payment_xmr != null && data.last_payment_xmr > 0 && (
            <span className="er-row"><span className="er-lbl">Last Payout</span><span className="er-val">{data.last_payment_xmr.toFixed(6)} XMR</span></span>
          )}
          {data.last_payment_time && (
            <span className="er-row"><span className="er-lbl">Paid At</span><span className="er-val">{new Date(data.last_payment_time).toLocaleDateString()}</span></span>
          )}
        </div>
      ) : (
        <div className="stat-sub">{data.note}</div>
      )}
      {xmrPrice && (
        <div className="stat-sub" style={{ marginTop: 4, opacity: 0.6, fontSize: '0.7rem' }}>
          XMR = ${xmrPrice.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
        </div>
      )}
      <div className="stat-sub" style={{ marginTop: 2, opacity: 0.45, fontSize: '0.68rem' }}>
        {isReal ? 'SupportXMR live · 5 min cache' : 'Formula estimate · connect wallet for live data'}
      </div>
    </NeonCard>
  );
}

// ─── Fleet Health Card ────────────────────────────────────────────────────────

export function FleetHealthCard({ health }: { health: FleetHealth }) {
  const accent = health.color === 'green' ? 'green' : health.color === 'amber' ? 'amber' : 'red';
  const barColor =
    health.color === 'green'
      ? 'var(--neon-green, #39ff14)'
      : health.color === 'amber'
      ? 'var(--neon-amber, #ffb020)'
      : '#ff3c50';

  return (
    <NeonCard accent={accent as any} className="fleet-health-card" hud>
      <div className="fh-header">
        <div>
          <span className="fh-label font-tech">FLEET HEALTH</span>
          <span className={`fh-status-chip fh-${health.color}`}>{health.label}</span>
        </div>
        <div className="fh-score" style={{ color: barColor }}>{health.score}</div>
      </div>
      <div className="fh-bar-track">
        <div
          className="fh-bar-fill"
          style={{ width: `${health.score}%`, background: barColor, boxShadow: `0 0 8px ${barColor}` }}
        />
      </div>
      <p className="fh-sentence">{health.sentence}</p>
    </NeonCard>
  );
}

// ─── Contribution Bars ───────────────────────────────────────────────────────

export function ContributionBars({
  bars,
  xmrPerDay,
  xmrPrice,
}: {
  bars: ContributionBar[];
  xmrPerDay?: number;
  xmrPrice?: number | null;
}) {
  if (bars.length === 0) return null;
  return (
    <NeonCard accent="cyan" className="section contrib-panel" hud>
      <h2 className="section-title font-display">
        <span className="section-ornament">◆</span> Contribution Map
        <span className="section-line" />
      </h2>
      <p className="form-hint" style={{ marginTop: 0 }}>
        Each bar shows a machine's share of total fleet hashrate.
      </p>
      <div className="contrib-list">
        {bars.map((b) => {
          const agentXmr = xmrPerDay != null ? xmrPerDay * (b.pct / 100) : null;
          const agentUsd = agentXmr != null && xmrPrice ? agentXmr * xmrPrice : null;
          return (
            <div key={b.id} className={`contrib-row${agentUsd != null ? ' has-usd' : ''}`}>
              <span className="contrib-name" title={b.name}>{b.name}</span>
              <div className="contrib-track">
                <div className="contrib-fill" style={{ width: `${b.pct}%` }} />
              </div>
              <span className="contrib-hash font-tech">{formatHashrate(b.hashrate)}</span>
              <span className="contrib-pct font-tech">{b.pct.toFixed(1)}%</span>
              {agentUsd != null && (
                <span className="contrib-usd font-tech">${agentUsd.toFixed(3)}/d</span>
              )}
            </div>
          );
        })}
      </div>
    </NeonCard>
  );
}

// ─── Underperformer List ──────────────────────────────────────────────────────

export function UnderperformerList({
  underperformers,
  medianHashrate,
}: {
  underperformers: Agent[];
  medianHashrate: number;
}) {
  const [restarting, setRestarting] = useState(false);
  const [msg, setMsg] = useState('');

  if (underperformers.length === 0) return null;

  const handleRestart = async () => {
    setRestarting(true);
    try {
      await api.sendBulkCommand(underperformers.map((a) => a.id), 'restart');
      setMsg(`Restart sent to ${underperformers.length} node(s).`);
    } catch {
      setMsg('Restart failed — check agent connections.');
    } finally {
      setRestarting(false);
      setTimeout(() => setMsg(''), 4000);
    }
  };

  return (
    <NeonCard accent="amber" className="section underperf-panel" hud>
      <div className="underperf-header">
        <h2 className="section-title font-display" style={{ margin: 0 }}>
          <span className="section-ornament">◆</span> Underperformers
          <span className="underperf-count"> ({underperformers.length})</span>
          <span className="section-line" />
        </h2>
        <button
          className="btn btn-outline underperf-restart-btn"
          onClick={handleRestart}
          disabled={restarting}
          title="Send restart command to all underperforming nodes"
        >
          {restarting ? 'Restarting…' : '↺ Restart All'}
        </button>
      </div>
      <p className="form-hint" style={{ marginTop: '0.25rem' }}>
        Nodes below 70% of fleet median ({formatHashrate(medianHashrate)}).
      </p>
      {msg && <p className="form-hint" style={{ color: 'var(--neon-amber)' }}>{msg}</p>}
      <div className="underperf-list">
        {underperformers.map((a) => (
          <div key={a.id} className="underperf-row">
            <span className={`status-dot ${a.status}`} />
            <span className="underperf-name">{a.name}</span>
            <span className="underperf-hash font-tech">{formatHashrate(a.hashrate_15m)}</span>
            <span className="underperf-ratio font-tech" style={{ color: '#ff3c50' }}>
              {medianHashrate > 0 ? `${((a.hashrate_15m / medianHashrate) * 100).toFixed(0)}% of median` : ''}
            </span>
          </div>
        ))}
      </div>
    </NeonCard>
  );
}

// ─── OS / Arch Breakdown ──────────────────────────────────────────────────────

export function OSArchBreakdown({ platforms }: { platforms: PlatformCount[] }) {
  if (platforms.length === 0) return null;
  const total = platforms.reduce((s, p) => s + p.count, 0);
  const colors = ['var(--neon-cyan)', 'var(--neon-purple)', 'var(--neon-amber)', 'var(--neon-green)', '#ff3c50'];
  return (
    <NeonCard accent="purple" className="os-arch-card" hud>
      <div className="stat-label font-tech">OS / Arch Breakdown</div>
      <div className="os-arch-bars">
        {platforms.map((p, i) => (
          <div key={p.key} className="os-arch-row">
            <span className="os-arch-label" style={{ color: colors[i % colors.length] }}>{p.label}</span>
            <div className="os-arch-track">
              <div
                className="os-arch-fill"
                style={{ width: `${(p.count / total) * 100}%`, background: colors[i % colors.length] }}
              />
            </div>
            <span className="os-arch-count font-tech">{p.count}</span>
          </div>
        ))}
      </div>
    </NeonCard>
  );
}

// ─── LAN Group View ───────────────────────────────────────────────────────────

export function LANGroupView({ groups }: { groups: SubnetGroup[] }) {
  if (groups.length < 2) return null;
  return (
    <NeonCard accent="green" className="lan-group-card" hud>
      <div className="stat-label font-tech">Network Segments</div>
      <div className="lan-group-list">
        {groups.map((g) => {
          const online = g.agents.filter((a) => a.status === 'online').length;
          const hash = g.agents.reduce((s, a) => s + a.hashrate_15m, 0);
          return (
            <div key={g.subnet} className="lan-group-row">
              <span className="lan-subnet font-tech">{g.subnet}</span>
              <span className="lan-meta">
                <span className="lan-online">{online}/{g.agents.length} online</span>
                <span className="lan-hash">{formatHashrate(hash)}</span>
              </span>
            </div>
          );
        })}
      </div>
    </NeonCard>
  );
}
