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

  const flows = useMemo(() => {
    return (data?.flows || []).map((f: any) => ({
      sid: f.sid || f.id || '',
      name: f.friendlyName || f.name || 'Untitled',
      status: f.status || 'draft',
      revision: f.revision || f.version || 1,
      dateUpdated: f.dateUpdated || f.dateModified || '',
      webhookUrl: f.webhookUrl || f.url || '',
    }));
  }, [data]);

  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="🔀 Studio Flows" subtitle={`${flows.length} flow${flows.length !== 1 ? 's' : ''}`} />
      <div className="card-grid card-grid-2">
        {flows.map((f: any) => (
          <div key={f.sid} className="card">
            <div className="card-body p-md">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
                <div style={{ fontWeight: 600, fontSize: 14, color: '#e2e8f0' }}>{f.name}</div>
                <StatusBadge label={f.status} variant={f.status === 'published' ? 'complete' : 'draft'} />
              </div>
              <div style={{ fontSize: 11, color: '#64748b', marginBottom: 4 }}>Version {f.revision}</div>
              {f.dateUpdated && <div style={{ fontSize: 11, color: '#64748b', marginBottom: 4 }}>Modified: {new Date(f.dateUpdated).toLocaleDateString()}</div>}
              {f.webhookUrl && (
                <div style={{ fontSize: 10, color: '#818cf8', fontFamily: "'SF Mono', monospace", overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 6 }}>
                  {f.webhookUrl}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
      {flows.length === 0 && <div className="empty-state"><div className="empty-icon">🔀</div><p>No Studio flows found</p></div>}
    </div>
  );
}
