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 [policies, setPolicies] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

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

  async function loadPolicies() {
    try {
      const result = await app.callTool('zendesk_list_sla_policies', {});
      const data = JSON.parse(result.content[0].text);
      setPolicies(data.sla_policies || []);
    } finally { setLoading(false); }
  }

  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <h1>SLA Dashboard</h1>
      {loading ? <div>Loading...</div> : (
        <div>
          <div style={{ marginBottom: 20 }}>Total Policies: {policies.length}</div>
          {policies.map(policy => (
            <div key={policy.id} style={{ border: '1px solid #ddd', borderRadius: 8, padding: 16, marginBottom: 16 }}>
              <h2 style={{ margin: 0, marginBottom: 8 }}>{policy.title}</h2>
              {policy.description && <p style={{ color: '#666' }}>{policy.description}</p>}
              <div style={{ marginTop: 12 }}>
                <strong>Metrics:</strong>
                <div style={{ marginTop: 8 }}>
                  {policy.policy_metrics?.map((metric: any, idx: number) => (
                    <div key={idx} style={{ padding: 8, background: '#f8f9fa', borderRadius: 4, marginBottom: 4 }}>
                      Priority: {metric.priority} | Metric: {metric.metric} | Target: {metric.target} mins
                      {metric.business_hours ? ' (Business hours)' : ''}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
      <details style={{ marginTop: 24 }}><summary>Text Fallback</summary>
        <pre>{JSON.stringify(policies, null, 2)}</pre></details>
    </div>
  );
}

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