import React, { useState, useCallback } from 'react';
import { useAuth } from '../auth/AuthProvider';
import { API_BASE } from '../auth/authConfig';

const HELP_BASE = 'https://mgmt.positivespend.com/api/help';

// ─── Service definitions ──────────────────────────────────────────────────────

const SERVICE_META = {
  gateway: {
    label: 'Gateway API', sub: 'portal.positivespend.com', tier: 'public', color: '#0066cc',
    mode: 'direct', url: `${API_BASE}/api/test/ping`,
    tech: '.NET 8 · Azure Container Apps · SQL Server',
  },
  management: {
    label: 'Management API', sub: 'mgmt.positivespend.com', tier: 'public', color: '#0ea5e9',
    mode: 'direct', url: 'https://mgmt.positivespend.com/health',
    tech: '.NET 8 · Azure Container Apps · SQL Server',
  },
  tech: {
    label: 'Tech (TestAPI)', sub: 'tech.positivespend.com', tier: 'public', color: '#64748b',
    mode: 'none',
    tech: 'React · MSAL · Azure Container Apps',
  },
  registration: {
    label: 'Registration', sub: 'regapi.positivespend.com', tier: 'registration', color: '#f97316',
    mode: 'direct', url: 'https://regapi.positivespend.com/api/health',
    tech: 'Azure Functions · .NET 8',
  },
  creative: {
    label: 'Creative', sub: 'OpenAI / DALL·E', tier: 'internal', color: '#8b5cf6',
    mode: 'provider', provider: 'creative',
    tech: 'OpenAI · DALL-E 3 · Unsplash · Azure Blob',
  },
  google: {
    label: 'Google Ads', sub: 'GoogleApi', tier: 'internal', color: '#4285f4',
    mode: 'provider', provider: 'google',
    tech: 'Google Ads .NET Client Library · Key Vault',
  },
  meta: {
    label: 'Meta Ads', sub: 'MetaApi', tier: 'internal', color: '#1877f2',
    mode: 'provider', provider: 'meta',
    tech: 'Meta Ads API · Business Manager',
  },
  tiktok: {
    label: 'TikTok Ads', sub: 'TikTokApi', tier: 'internal', color: '#2d2d2d',
    mode: 'provider', provider: 'tiktok',
    tech: 'TikTok Ads API · Business Center',
  },
  intelligence: {
    label: 'Intelligence', sub: 'IntelligenceApi', tier: 'internal', color: '#10b981',
    mode: 'provider', provider: 'intelligence',
    tech: '.NET 8 · Azure Container Apps · Internal Only',
  },
};

const TIER_PUBLIC   = ['management', 'tech', 'gateway'];
const TIER_REG      = ['registration'];
const TIER_INTERNAL = ['creative', 'google', 'meta', 'tiktok', 'intelligence'];
const CHECKABLE     = [...TIER_PUBLIC, ...TIER_REG, ...TIER_INTERNAL].filter(
  id => SERVICE_META[id].mode !== 'none'
);

// ─── Status helpers ───────────────────────────────────────────────────────────

const statusColor = (s) => ({ healthy: '#22c55e', error: '#f59e0b', unreachable: '#ef4444' }[s] || '#cbd5e1');
const statusLabel = (s) => ({ healthy: 'Healthy', error: 'Error', unreachable: 'Unreachable' }[s] || 'Not checked');

// ─── Service Node ─────────────────────────────────────────────────────────────

function ServiceNode({ id, result, onClick }) {
  const svc = SERVICE_META[id];
  const sc  = statusColor(result?.status);

  return (
    <button
      className="svc-node"
      onClick={() => onClick(id)}
      style={{ borderColor: result ? sc : undefined }}
    >
      {result && (
        <span className="svc-node-dot" style={{ background: sc, boxShadow: `0 0 5px ${sc}` }} />
      )}
      <span className="svc-node-name" style={{ color: svc.color }}>{svc.label}</span>
      <span className="svc-node-sub">{svc.sub}</span>
      {result?.ms != null && <span className="svc-node-ms">{result.ms}ms</span>}
    </button>
  );
}

// ─── Service Popup ────────────────────────────────────────────────────────────

function ServicePopup({ id, result, onClose }) {
  const svc = SERVICE_META[id];
  const sc  = statusColor(result?.status);

  const [helpTitle, setHelpTitle] = React.useState(null);
  const [helpBody,  setHelpBody]  = React.useState(null);
  const [helpLoading, setHelpLoading] = React.useState(true);

  React.useEffect(() => {
    setHelpLoading(true);
    fetch(`${HELP_BASE}/service.${id}`)
      .then(r => r.json())
      .then(data => {
        setHelpTitle(data.title || svc.label);
        setHelpBody(data.body || '<p>No information available for this topic yet.</p>');
      })
      .catch(() => {
        setHelpBody('<p>No information available for this topic yet.</p>');
      })
      .finally(() => setHelpLoading(false));
  }, [id]);

  const handleBackdrop = (e) => { if (e.target === e.currentTarget) onClose(); };

  return (
    <div className="svc-popup-backdrop" onClick={handleBackdrop}>
      <div className="svc-popup">
        <div className="svc-popup-bar" style={{ background: svc.color }} />

        <div className="svc-popup-head">
          <div>
            <div className="svc-popup-title" style={{ color: svc.color }}>{svc.label}</div>
            <div className="svc-popup-sub">{svc.sub}</div>
          </div>
          <button className="svc-popup-close" onClick={onClose}>✕</button>
        </div>

        {/* Status row */}
        <div className="svc-popup-status-row">
          <div className="svc-popup-stat">
            <div className="svc-popup-stat-label">STATUS</div>
            <div className="svc-popup-stat-value" style={{ color: result ? sc : '#94a3b8' }}>
              {result && <span className="svc-popup-dot" style={{ background: sc, boxShadow: `0 0 4px ${sc}` }} />}
              {statusLabel(result?.status)}
            </div>
          </div>
          {result?.ms != null && (
            <div className="svc-popup-stat">
              <div className="svc-popup-stat-label">RESPONSE</div>
              <div className="svc-popup-stat-value">{result.ms}ms</div>
            </div>
          )}
          <div className="svc-popup-stat">
            <div className="svc-popup-stat-label">TIER</div>
            <div className="svc-popup-stat-value" style={{ color: '#64748b' }}>
              { svc.tier === 'public' ? 'Public' : svc.tier === 'registration' ? 'Registration' : 'Internal' }
            </div>
          </div>
        </div>

        {/* Health endpoint */}
        {svc.mode !== 'none' && (
          <div className="svc-popup-section">
            <div className="svc-popup-section-label">HEALTH ENDPOINT</div>
            <code className="svc-popup-code">
              {svc.mode === 'direct'
                ? svc.url
                : `POST ${API_BASE}/api/execution/request  →  provider: "${svc.provider}"  →  Ping`}
            </code>
          </div>
        )}

        {/* About — from help DB */}
        <div className="svc-popup-section">
          <div className="svc-popup-section-label">ABOUT</div>
          {helpLoading
            ? <p className="svc-popup-loading">Loading…</p>
            : <div
                className="svc-popup-about"
                dangerouslySetInnerHTML={{ __html: helpBody }}
              />
          }
        </div>

        {/* Stack */}
        <div className="svc-popup-section">
          <div className="svc-popup-section-label">STACK</div>
          <div className="svc-popup-tech">{svc.tech}</div>
        </div>

        {/* Error detail */}
        {result?.message && (
          <div className="svc-popup-section">
            <div className="svc-popup-section-label">DETAIL</div>
            <code className="svc-popup-code svc-popup-error">{result.message}</code>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Architecture Diagram ─────────────────────────────────────────────────────

function ArchDiagram({ results, onNodeClick }) {
  return (
    <div className="arch2-wrap">
      <div className="arch2-title">Platform Architecture</div>

      <div className="arch2-top">
        {/* Public tier */}
        <div className="arch2-tier" style={{ flex: 1 }}>
          <div className="arch2-tier-label">Public Access</div>
          <div className="arch2-tier-nodes">
            {TIER_PUBLIC.map(id => (
              <ServiceNode key={id} id={id} result={results[id]} onClick={onNodeClick} />
            ))}
          </div>
          <div className="arch2-db-connector">
            <div className="arch2-vline" />
            <div className="arch2-db">🗄 SQL DB</div>
          </div>
        </div>

        <div className="arch2-pillar-sep" />

        {/* Registration tier */}
        <div className="arch2-tier arch2-tier-reg">
          <div className="arch2-tier-label">Registration</div>
          <div className="arch2-tier-nodes">
            {TIER_REG.map(id => (
              <ServiceNode key={id} id={id} result={results[id]} onClick={onNodeClick} />
            ))}
          </div>
          <div className="arch2-db-connector">
            <div className="arch2-vline" />
            <div className="arch2-db">🗄 Reg DB</div>
          </div>
        </div>
      </div>

      {/* Arrow */}
      <div className="arch2-arrow-zone">
        <div className="arch2-arrow-line">
          <span className="arch2-arrow-label">internal routing via Gateway</span>
        </div>
      </div>

      {/* Internal tier */}
      <div className="arch2-tier arch2-tier-internal">
        <div className="arch2-tier-label">Internal Only — Azure Container Apps</div>
        <div className="arch2-tier-nodes arch2-tier-nodes-center">
          {TIER_INTERNAL.map(id => (
            <ServiceNode key={id} id={id} result={results[id]} onClick={onNodeClick} />
          ))}
        </div>
      </div>

      {/* Legend */}
      <div className="arch2-legend">
        {[['#22c55e','Healthy'],['#f59e0b','Error'],['#ef4444','Unreachable'],['#cbd5e1','Not checked']].map(([c,l]) => (
          <span key={l} className="arch2-legend-item">
            <span className="arch2-legend-dot" style={{ background: c }} />{l}
          </span>
        ))}
      </div>
    </div>
  );
}

// ─── Main Dashboard ───────────────────────────────────────────────────────────

export default function HealthDashboard() {
  const { getIdToken } = useAuth();
  const [results,   setResults]   = useState({});
  const [checking,  setChecking]  = useState(false);
  const [lastCheck, setLastCheck] = useState(null);
  const [popup,     setPopup]     = useState(null);

  const checkAll = useCallback(async () => {
    setChecking(true);
    const next = {};
    const token = await getIdToken();

    await Promise.all(
      CHECKABLE.map(async (id) => {
        const svc   = SERVICE_META[id];
        const start = performance.now();
        try {
          let resp;
          if (svc.mode === 'direct') {
            resp = await fetch(svc.url, { signal: AbortSignal.timeout(8000) });
          } else {
            resp = await fetch(`${API_BASE}/api/execution/request`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                ...(token ? { Authorization: `Bearer ${token}` } : {})
              },
              body: JSON.stringify({ provider: svc.provider, operation: 'Ping', payload: {} }),
              signal: AbortSignal.timeout(8000)
            });
          }
          const ms = Math.round(performance.now() - start);
          if (resp.ok) {
            let data = null;
            try { data = await resp.json(); } catch {}
            next[id] = { status: 'healthy', ms, data, httpStatus: resp.status };
          } else {
            let text = '';
            try { text = await resp.text(); } catch {}
            next[id] = { status: 'error', ms, httpStatus: resp.status, message: `HTTP ${resp.status}: ${text.substring(0, 200)}` };
          }
        } catch (err) {
          const ms = Math.round(performance.now() - start);
          next[id] = { status: 'unreachable', ms, message: err.name === 'TimeoutError' ? 'Timed out (8s)' : err.message };
        }
      })
    );

    setResults(next);
    setLastCheck(new Date());
    setChecking(false);
  }, [getIdToken]);

  const healthyCount = Object.values(results).filter(r => r.status === 'healthy').length;
  const totalChecked  = Object.keys(results).length;

  return (
    <div className="health-dashboard">
      <div className="health-header">
        <div className="health-title-row">
          <h3 className="health-title">⚡ Service Health</h3>
          {totalChecked > 0 && (
            <span className={`health-summary ${healthyCount === totalChecked ? 'all-healthy' : 'has-issues'}`}>
              {healthyCount}/{totalChecked} services up
            </span>
          )}
        </div>
        <div className="health-actions">
          {lastCheck && (
            <span className="health-timestamp">Last check: {lastCheck.toLocaleTimeString()}</span>
          )}
          <button
            className="token-btn token-btn-primary"
            onClick={checkAll}
            disabled={checking}
            style={{ minWidth: 120 }}
          >
            {checking ? '⟳ Checking…' : '▶ Check All'}
          </button>
        </div>
      </div>

      {totalChecked === 0 && (
        <p className="arch2-hint">Click any node for details · Run Check All to test live status</p>
      )}

      <ArchDiagram results={results} onNodeClick={setPopup} />

      {popup && (
        <ServicePopup
          id={popup}
          result={results[popup]}
          onClose={() => setPopup(null)}
        />
      )}
    </div>
  );
}
