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 { ProgressBar } from '../../components/data/ProgressBar';
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: 'Queue Manager', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const queues = useMemo(() => {
    return (data?.queues || data?.taskQueues || []).map((q: any) => ({
      sid: q.sid || q.id || '',
      name: q.friendlyName || q.name || 'Queue',
      size: q.currentSize ?? q.size ?? q.tasksInQueue ?? 0,
      maxSize: q.maxSize ?? q.maxCapacity ?? 100,
      longestWait: q.longestWait ?? q.avgWait ?? '—',
      agentsAvailable: q.agentsAvailable ?? q.availableWorkers ?? 0,
      agentsTotal: q.agentsTotal ?? q.totalWorkers ?? 0,
    }));
  }, [data]);

  const totalInQueue = queues.reduce((s: number, q: any) => s + q.size, 0);
  const totalAgents = queues.reduce((s: number, q: any) => s + q.agentsAvailable, 0);

  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="📋 Queue Manager" subtitle={`${queues.length} queues`} gradient />
      <StatsGrid columns={3}>
        <MetricCard label="Total in Queue" value={String(totalInQueue)} color="blue" />
        <MetricCard label="Agents Available" value={String(totalAgents)} color="green" />
        <MetricCard label="Active Queues" value={String(queues.length)} color="purple" />
      </StatsGrid>
      {queues.map((q: any) => (
        <div key={q.sid} className="card" style={{ marginBottom: 8 }}>
          <div className="card-body p-md">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <div style={{ fontWeight: 600, fontSize: 14, color: '#e2e8f0' }}>{q.name}</div>
              <div style={{ fontSize: 12, color: '#94a3b8' }}>{q.agentsAvailable} / {q.agentsTotal} agents</div>
            </div>
            <ProgressBar
              label="Queue Utilization"
              value={q.size}
              max={q.maxSize || 1}
              color={q.size / (q.maxSize || 1) > 0.8 ? 'red' : q.size / (q.maxSize || 1) > 0.5 ? 'yellow' : 'blue'}
            />
            <div style={{ display: 'flex', gap: 16, fontSize: 11, color: '#64748b', marginTop: 4 }}>
              <span>Tasks: <strong style={{ color: '#e2e8f0' }}>{q.size}</strong></span>
              <span>Longest Wait: <strong style={{ color: '#e2e8f0' }}>{q.longestWait}</strong></span>
            </div>
          </div>
        </div>
      ))}
      {queues.length === 0 && <div className="empty-state"><div className="empty-icon">📋</div><p>No queues found</p></div>}
    </div>
  );
}
