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: 'Agent Status', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const agents = useMemo(() => {
    return (data?.agents || data?.workers || []).map((a: any) => ({
      sid: a.sid || a.id || '',
      name: a.friendlyName || a.name || 'Agent',
      activity: a.activityName || a.activity || a.status || 'offline',
      currentTask: a.currentTask || a.taskName || '—',
      timeInState: a.timeInState || a.duration || '—',
    }));
  }, [data]);

  const counts = useMemo(() => {
    const available = agents.filter((a: any) => ['available', 'idle', 'ready'].includes(a.activity.toLowerCase())).length;
    const busy = agents.filter((a: any) => ['busy', 'reserved', 'on-task', 'wrapup'].includes(a.activity.toLowerCase())).length;
    const offline = agents.filter((a: any) => ['offline', 'break', 'unavailable'].includes(a.activity.toLowerCase())).length;
    return { available, busy, offline, total: agents.length };
  }, [agents]);

  const getStatusColor = (activity: string) => {
    const a = activity.toLowerCase();
    if (['available', 'idle', 'ready'].includes(a)) return '#22c55e';
    if (['busy', 'reserved', 'on-task', 'wrapup'].includes(a)) return '#f59e0b';
    return '#64748b';
  };

  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="👥 Agent Status" subtitle={`${counts.total} agents`} gradient />
      <StatsGrid columns={3}>
        <MetricCard label="Available" value={String(counts.available)} color="green" />
        <MetricCard label="Busy" value={String(counts.busy)} color="yellow" />
        <MetricCard label="Offline" value={String(counts.offline)} color="red" />
      </StatsGrid>
      <div className="card-grid card-grid-2">
        {agents.map((a: any) => (
          <div key={a.sid} className="card">
            <div className="card-body p-md">
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <div style={{ width: 12, height: 12, borderRadius: '50%', background: getStatusColor(a.activity), flexShrink: 0 }} />
                <div style={{ fontWeight: 600, fontSize: 14, color: '#e2e8f0' }}>{a.name}</div>
              </div>
              <div style={{ fontSize: 12, color: '#94a3b8', marginBottom: 4 }}>
                Status: <span style={{ color: getStatusColor(a.activity), fontWeight: 600 }}>{a.activity}</span>
              </div>
              <div style={{ fontSize: 11, color: '#64748b' }}>Task: {a.currentTask}</div>
              <div style={{ fontSize: 11, color: '#64748b' }}>Time in state: {a.timeInState}</div>
            </div>
          </div>
        ))}
      </div>
      {agents.length === 0 && <div className="empty-state"><div className="empty-icon">👥</div><p>No agents found</p></div>}
    </div>
  );
}
