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

function App() {
  const app = useApp();
  const [query, setQuery] = useState('');
  const [tab, setTab] = useState<'all' | 'tickets' | 'users' | 'orgs'>('all');
  const [results, setResults] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  async function search() {
    if (!query) return;
    try {
      setLoading(true);
      const toolMap = { all: 'zendesk_search', tickets: 'zendesk_search_tickets', users: 'zendesk_search_users', orgs: 'zendesk_search_organizations' };
      const result = await app.callTool(toolMap[tab], { query });
      const data = JSON.parse(result.content[0].text);
      setResults(data.results || data.tickets || data.users || data.organizations || []);
    } finally { setLoading(false); }
  }

  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <h1>Search Zendesk</h1>
      <div style={{ marginBottom: 16 }}>
        <input value={query} onChange={e => setQuery(e.target.value)} onKeyPress={e => e.key === 'Enter' && search()}
          placeholder="Search..." style={{ padding: 8, width: 400, marginRight: 8 }} />
        <button onClick={search} disabled={loading} style={{ padding: 8 }}>
          {loading ? 'Searching...' : 'Search'}
        </button>
      </div>
      <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
        {(['all', 'tickets', 'users', 'orgs'] as const).map(t => (
          <button key={t} onClick={() => setTab(t)} style={{
            padding: 8, background: tab === t ? '#007bff' : '#f0f0f0',
            color: tab === t ? 'white' : 'black', border: 'none', borderRadius: 4, cursor: 'pointer'
          }}>{t.charAt(0).toUpperCase() + t.slice(1)}</button>
        ))}
      </div>
      {results.length > 0 && (
        <div>
          <div style={{ marginBottom: 12 }}>Found {results.length} results</div>
          {results.map((r, idx) => (
            <div key={idx} style={{ border: '1px solid #ddd', borderRadius: 4, padding: 12, marginBottom: 8 }}>
              <div style={{ fontWeight: 'bold' }}>{r.name || r.subject || r.title || 'Result'}</div>
              <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
                ID: #{r.id} | Type: {r.result_type || 'unknown'}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

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