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 [tickets, setTickets] = useState<any[]>([]);
  const [filter, setFilter] = useState({ status: '', priority: '' });
  const [loading, setLoading] = useState(true);

  useEffect(() => { loadTickets(); }, [filter]);

  async function loadTickets() {
    try {
      setLoading(true);
      const result = await app.callTool('zendesk_list_tickets', { page_size: 50 });
      const data = JSON.parse(result.content[0].text);
      let list = data.tickets || [];
      if (filter.status) list = list.filter((t: any) => t.status === filter.status);
      if (filter.priority) list = list.filter((t: any) => t.priority === filter.priority);
      setTickets(list);
    } finally { setLoading(false); }
  }

  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <h1>Ticket Grid</h1>
      <div style={{ marginBottom: 16, display: 'flex', gap: 12 }}>
        <select value={filter.status} onChange={e => setFilter({ ...filter, status: e.target.value })} style={{ padding: 8 }}>
          <option value="">All Statuses</option>
          {['new', 'open', 'pending', 'solved', 'closed'].map(s => <option key={s} value={s}>{s}</option>)}
        </select>
        <select value={filter.priority} onChange={e => setFilter({ ...filter, priority: e.target.value })} style={{ padding: 8 }}>
          <option value="">All Priorities</option>
          {['urgent', 'high', 'normal', 'low'].map(p => <option key={p} value={p}>{p}</option>)}
        </select>
      </div>
      {loading ? <div>Loading...</div> : (
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr style={{ background: '#f5f5f5' }}>
            {['ID', 'Subject', 'Status', 'Priority', 'Requester', 'Updated'].map(h => (
              <th key={h} style={{ padding: 12, textAlign: 'left' }}>{h}</th>
            ))}
          </tr></thead>
          <tbody>{tickets.map(t => (
            <tr key={t.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: 12 }}>#{t.id}</td>
              <td style={{ padding: 12 }}>{t.subject || '(No subject)'}</td>
              <td style={{ padding: 12 }}>{t.status}</td>
              <td style={{ padding: 12 }}>{t.priority || 'normal'}</td>
              <td style={{ padding: 12 }}>#{t.requester_id}</td>
              <td style={{ padding: 12 }}>{new Date(t.updated_at).toLocaleDateString()}</td>
            </tr>
          ))}</tbody>
        </table>
      )}
      <div style={{ marginTop: 16 }}>Total: {tickets.length}</div>
      <details style={{ marginTop: 24 }}><summary>Text Fallback</summary>
        <pre>{JSON.stringify(tickets, null, 2)}</pre></details>
    </div>
  );
}

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