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 '../../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;
}

interface FlowStep {
  name: string;
  type: string;
  description?: string;
  transitions?: { event: string; next: string }[];
}

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

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

  const steps: FlowStep[] = useMemo(() => {
    if (!data) return [];
    // Handle Studio flow states/steps
    const states = data.states || data.steps || data.widgets || [];
    if (Array.isArray(states)) return states.map((s: any) => ({
      name: s.name || s.friendlyName || s.label || '',
      type: s.type || 'action',
      description: s.description || s.properties?.body || '',
      transitions: (s.transitions || []).map((t: any) => ({
        event: t.event || t.condition || '',
        next: t.next || t.target || '',
      })),
    }));
    return [];
  }, [data]);

  const flowName = data?.friendlyName || data?.flowName || data?.name || 'Studio Flow';

  const getNodeClass = (type: string) => {
    const t = type.toLowerCase();
    if (t.includes('trigger') || t.includes('start')) return 'flow-node-start';
    if (t.includes('split') || t.includes('condition') || t.includes('gather')) return 'flow-node-condition';
    if (t.includes('end') || t.includes('subflow')) return 'flow-node-end';
    return 'flow-node-action';
  };

  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={`🔀 ${flowName}`} subtitle="Studio Flow Visualization" />
      <div className="flow-diagram">
        <div className="flow-container">
          {steps.map((step, i) => (
            <React.Fragment key={i}>
              <div className={`flow-node ${getNodeClass(step.type)}`}>
                <div className="flow-node-label">{step.name}</div>
                <div className="flow-node-desc">{step.type}</div>
                {step.description && <div style={{ fontSize: 10, color: '#64748b', marginTop: 4 }}>{step.description.slice(0, 60)}{step.description.length > 60 ? '…' : ''}</div>}
              </div>
              {i < steps.length - 1 && (
                <div className="flow-arrow">
                  <span>↓</span>
                  {step.transitions && step.transitions.length > 0 && (
                    <span className="flow-edge-label">{step.transitions[0]?.event || ''}</span>
                  )}
                </div>
              )}
            </React.Fragment>
          ))}
          {steps.length === 0 && <div style={{ textAlign: 'center', color: '#64748b', padding: 40 }}>No flow steps to display</div>}
        </div>
      </div>
      {/* Branching connections sidebar */}
      {steps.some(s => (s.transitions?.length || 0) > 1) && (
        <div className="card" style={{ marginTop: 8 }}>
          <div className="card-header"><h2 className="card-title">Branching Connections</h2></div>
          <div className="card-body p-md">
            {steps.filter(s => (s.transitions?.length || 0) > 1).map((s, i) => (
              <div key={i} style={{ marginBottom: 8 }}>
                <div style={{ fontWeight: 600, fontSize: 12, color: '#e2e8f0' }}>{s.name}</div>
                {s.transitions!.map((t, j) => (
                  <div key={j} style={{ fontSize: 11, color: '#94a3b8', paddingLeft: 12 }}>
                    {t.event || 'default'} → <span style={{ color: '#818cf8' }}>{t.next}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
