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 [ratings, setRatings] = useState<any[]>([]);
  const [stats, setStats] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);

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

  async function loadRatings() {
    try {
      const result = await app.callTool('zendesk_list_satisfaction_ratings', {});
      const data = JSON.parse(result.content[0].text);
      const ratingList = data.satisfaction_ratings || [];
      setRatings(ratingList);
      
      const scoreCounts: Record<string, number> = {};
      ratingList.forEach((r: any) => {
        scoreCounts[r.score] = (scoreCounts[r.score] || 0) + 1;
      });
      setStats(scoreCounts);
    } finally { setLoading(false); }
  }

  const goodCount = stats.good || 0;
  const badCount = stats.bad || 0;
  const total = goodCount + badCount;
  const percentage = total > 0 ? ((goodCount / total) * 100).toFixed(1) : '0';

  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <h1>Satisfaction Dashboard</h1>
      {loading ? <div>Loading...</div> : (
        <div>
          <div style={{ display: 'flex', gap: 16, marginBottom: 24 }}>
            <div style={{ padding: 20, background: '#28a745', color: 'white', borderRadius: 8, flex: 1 }}>
              <div style={{ fontSize: 32, fontWeight: 'bold' }}>{percentage}%</div>
              <div>Satisfaction Rate</div>
            </div>
            <div style={{ padding: 20, background: '#007bff', color: 'white', borderRadius: 8, flex: 1 }}>
              <div style={{ fontSize: 32, fontWeight: 'bold' }}>{goodCount}</div>
              <div>Good Ratings</div>
            </div>
            <div style={{ padding: 20, background: '#dc3545', color: 'white', borderRadius: 8, flex: 1 }}>
              <div style={{ fontSize: 32, fontWeight: 'bold' }}>{badCount}</div>
              <div>Bad Ratings</div>
            </div>
          </div>

          <h2>Recent Ratings</h2>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr style={{ background: '#f5f5f5' }}>
              {['Ticket', 'Score', 'Assignee', 'Comment', 'Date'].map(h => (
                <th key={h} style={{ padding: 12, textAlign: 'left' }}>{h}</th>
              ))}
            </tr></thead>
            <tbody>{ratings.slice(0, 50).map(r => (
              <tr key={r.id} style={{ borderBottom: '1px solid #eee' }}>
                <td style={{ padding: 12 }}>#{r.ticket_id}</td>
                <td style={{ padding: 12 }}>
                  <span style={{ color: r.score === 'good' ? '#28a745' : r.score === 'bad' ? '#dc3545' : '#666' }}>
                    {r.score}
                  </span>
                </td>
                <td style={{ padding: 12 }}>#{r.assignee_id}</td>
                <td style={{ padding: 12 }}>{r.comment || '-'}</td>
                <td style={{ padding: 12 }}>{new Date(r.created_at).toLocaleDateString()}</td>
              </tr>
            ))}</tbody>
          </table>
        </div>
      )}
    </div>
  );
}

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