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 [users, setUsers] = useState<any[]>([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);

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

  async function loadUsers() {
    try {
      setLoading(true);
      const result = await app.callTool('zendesk_list_users', {});
      const data = JSON.parse(result.content[0].text);
      setUsers(data.users || []);
    } finally { setLoading(false); }
  }

  async function searchUsers() {
    if (!search) return loadUsers();
    try {
      setLoading(true);
      const result = await app.callTool('zendesk_search_users', { query: search });
      const data = JSON.parse(result.content[0].text);
      setUsers(data.users || []);
    } finally { setLoading(false); }
  }

  const filtered = users.filter(u => 
    !search || u.name?.toLowerCase().includes(search.toLowerCase()) || u.email?.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <h1>User Directory</h1>
      <div style={{ marginBottom: 16 }}>
        <input value={search} onChange={e => setSearch(e.target.value)} onKeyPress={e => e.key === 'Enter' && searchUsers()}
          placeholder="Search users..." style={{ padding: 8, width: 300, marginRight: 8 }} />
        <button onClick={searchUsers} style={{ padding: 8 }}>Search</button>
      </div>
      {loading ? <div>Loading...</div> : (
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr style={{ background: '#f5f5f5' }}>
            {['ID', 'Name', 'Email', 'Role', 'Organization', 'Created'].map(h => (
              <th key={h} style={{ padding: 12, textAlign: 'left' }}>{h}</th>
            ))}
          </tr></thead>
          <tbody>{filtered.map(u => (
            <tr key={u.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: 12 }}>#{u.id}</td>
              <td style={{ padding: 12 }}>{u.name}</td>
              <td style={{ padding: 12 }}>{u.email || '-'}</td>
              <td style={{ padding: 12 }}>{u.role}</td>
              <td style={{ padding: 12 }}>{u.organization_id ? `#${u.organization_id}` : '-'}</td>
              <td style={{ padding: 12 }}>{new Date(u.created_at).toLocaleDateString()}</td>
            </tr>
          ))}</tbody>
        </table>
      )}
      <div style={{ marginTop: 16 }}>Total: {filtered.length}</div>
    </div>
  );
}

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