import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { PageHeader } from '../../components/layout/PageHeader';
import { StatsGrid } from '../../components/layout/StatsGrid';
import { MetricCard } from '../../components/data/MetricCard';
import '../../styles/base.css';
import '../../styles/interactive.css';

function extractData(result: CallToolResult): any {
  const sc = (result as any).structuredContent;
  if (sc) return sc;
  for (const item of result.content || []) {
    if (item.type === 'text') { try { return JSON.parse(item.text); } catch {} }
  }
  return null;
}

export function App() {
  const [data, setData] = useState<any>((window as any).__MCP_APP_DATA__ || null);

  const { isConnected, error } = useApp({
    appInfo: { name: 'Health Check', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const services = useMemo(() => {
    const defaults = ['Messaging', 'Voice', 'Studio', 'Lookup', 'TaskRouter', 'Verify', 'Functions', 'Conversations'];
    if (data?.services) {
      return (data.services || []).map((s: any) => ({
        name: s.name || '',
        status: s.status || 'unknown',
        uptime: s.uptime ?? s.uptimePercent ?? '—',
        latency: s.latency || s.responseTime || '—',
        lastChecked: s.lastChecked || s.timestamp || '',
      }));
    }
    // Fallback: build from top-level data
    return defaults.map(name => ({
      name,
      status: data?.[name.toLowerCase()]?.status || data?.status || 'operational',
      uptime: data?.[name.toLowerCase()]?.uptime || '99.99%',
      latency: data?.[name.toLowerCase()]?.latency || '—',
      lastChecked: '',
    }));
  }, [data]);

  const getStatusInfo = (status: string) => {
    const s = status.toLowerCase();
    if (s === 'operational' || s === 'healthy' || s === 'up') return { dot: '#22c55e', label: 'Operational', bg: 'rgba(34,197,94,0.1)' };
    if (s === 'degraded' || s === 'slow' || s === 'warning') return { dot: '#f59e0b', label: 'Degraded', bg: 'rgba(245,158,11,0.1)' };
    if (s === 'down' || s === 'outage' || s === 'error') return { dot: '#ef4444', label: 'Outage', bg: 'rgba(239,68,68,0.1)' };
    return { dot: '#64748b', label: status, bg: 'rgba(100,116,139,0.1)' };
  };

  const healthyCount = services.filter((s: any) => ['operational', 'healthy', 'up'].includes(s.status.toLowerCase())).length;
  const overallStatus = healthyCount === services.length ? 'All Systems Operational' : `${healthyCount}/${services.length} Healthy`;

  if (error) return <div className="error-state"><h3>Error</h3><p>{error.message}</p></div>;
  if (!isConnected) return <div className="loading-state"><div className="loading-spinner" /><p>Connecting...</p></div>;
  if (!data) return <div className="loading-state"><div className="loading-spinner" /><p>Waiting for data...</p></div>;

  return (
    <div>
      <PageHeader title="🏥 Service Health" subtitle={overallStatus} status={healthyCount === services.length ? 'ALL OK' : 'DEGRADED'} statusVariant={healthyCount === services.length ? 'complete' : 'error'} />
      <StatsGrid columns={3}>
        <MetricCard label="Healthy" value={String(healthyCount)} color="green" />
        <MetricCard label="Degraded" value={String(services.filter((s: any) => ['degraded', 'slow', 'warning'].includes(s.status.toLowerCase())).length)} color="yellow" />
        <MetricCard label="Down" value={String(services.filter((s: any) => ['down', 'outage', 'error'].includes(s.status.toLowerCase())).length)} color="red" />
      </StatsGrid>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {services.map((s: any, i: number) => {
          const info = getStatusInfo(s.status);
          return (
            <div key={i} className="card" style={{ marginBottom: 0 }}>
              <div className="card-body p-md" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ width: 12, height: 12, borderRadius: '50%', background: info.dot, boxShadow: `0 0 6px ${info.dot}44` }} />
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 13, color: '#e2e8f0' }}>{s.name}</div>
                    <div style={{ fontSize: 11, color: '#64748b' }}>Uptime: {s.uptime}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  {s.latency !== '—' && <span style={{ fontSize: 11, color: '#94a3b8' }}>{s.latency}</span>}
                  <span style={{ padding: '3px 10px', borderRadius: 9999, fontSize: 11, fontWeight: 600, background: info.bg, color: info.dot }}>{info.label}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
