import React, { useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { useApp } from '@modelcontextprotocol/ext-apps/react';

function App() {
  const app = useApp();
  const [macros, setMacros] = useState<any[]>([]);
  const [selectedMacro, setSelectedMacro] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => { loadMacros(); }, []);

  async function loadMacros() {
    try {
      const result = await app.callTool('zendesk_list_macros', {});
      const data = JSON.parse(result.content[0].text);
      setMacros(data.macros || []);
    } finally { setLoading(false); }
  }

  async function viewMacro(id: number) {
    const result = await app.callTool('zendesk_get_macro', { macro_id: id });
    const data = JSON.parse(result.content[0].text);
    setSelectedMacro(data);
  }

  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <h1>Macro Manager</h1>
      {loading ? <div>Loading...</div> : (
        <div style={{ display: 'flex', gap: 20 }}>
          <div style={{ flex: 1 }}>
            <h2>Macros ({macros.length})</h2>
            <div style={{ maxHeight: 600, overflowY: 'auto' }}>
              {macros.map(m => (
                <div key={m.id} onClick={() => viewMacro(m.id)} style={{
                  padding: 12, border: '1px solid #ddd', borderRadius: 4, marginBottom: 8,
                  cursor: 'pointer', background: selectedMacro?.id === m.id ? '#e7f3ff' : 'white'
                }}>
                  <div style={{ fontWeight: 'bold' }}>{m.title}</div>
                  <div style={{ fontSize: 12, color: '#666' }}>
                    {m.active ? '✓ Active' : '✗ Inactive'} | {m.actions?.length || 0} actions
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ flex: 1 }}>
            {selectedMacro ? (
              <div>
                <h2>{selectedMacro.title}</h2>
                {selectedMacro.description && <p style={{ color: '#666' }}>{selectedMacro.description}</p>}
                <div style={{ marginTop: 16 }}>
                  <strong>Actions:</strong>
                  {selectedMacro.actions?.map((action: any, idx: number) => (
                    <div key={idx} style={{ padding: 8, background: '#f8f9fa', borderRadius: 4, marginTop: 8 }}>
                      <div><strong>{action.field}</strong></div>
                      <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>{JSON.stringify(action.value)}</div>
                    </div>
                  ))}
                </div>
              </div>
            ) : <div style={{ color: '#999' }}>Select a macro to view details</div>}
          </div>
        </div>
      )}
    </div>
  );
}

createRoot(document.getElementById('root')!).render(<App />);
