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

interface Ticket {
  id: number;
  subject: string;
  status: string;
  priority: string;
  created_at: string;
  updated_at: string;
  requester_id: number;
}

function App() {
  const app = useApp();
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [stats, setStats] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);

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

  async function loadData() {
    try {
      setLoading(true);
      
      // Get recent tickets
      const result = await app.callTool('zendesk_list_tickets', { page_size: 20, sort_by: 'updated_at', sort_order: 'desc' });
      const data = JSON.parse(result.content[0].text);
      const ticketList = data.tickets || [];
      setTickets(ticketList);
      
      // Calculate stats
      const statusCounts: Record<string, number> = {};
      ticketList.forEach((t: Ticket) => {
        statusCounts[t.status] = (statusCounts[t.status] || 0) + 1;
      });
      setStats(statusCounts);
    } catch (error) {
      console.error('Failed to load tickets:', error);
    } finally {
      setLoading(false);
    }
  }

  if (loading) {
    return <div style={{ padding: 20 }}>Loading...</div>;
  }

  return (
    <div style={{ fontFamily: 'system-ui, sans-serif', padding: 20 }}>
      <h1>Ticket Dashboard</h1>
      
      {/* Stats cards */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        {Object.entries(stats).map(([status, count]) => (
          <div key={status} style={{
            padding: 16,
            background: getStatusColor(status),
            borderRadius: 8,
            minWidth: 120,
            color: 'white'
          }}>
            <div style={{ fontSize: 32, fontWeight: 'bold' }}>{count}</div>
            <div style={{ textTransform: 'capitalize' }}>{status}</div>
          </div>
        ))}
      </div>

      {/* Recent tickets table */}
      <h2>Recent Tickets</h2>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr style={{ background: '#f5f5f5', textAlign: 'left' }}>
            <th style={{ padding: 12, borderBottom: '2px solid #ddd' }}>ID</th>
            <th style={{ padding: 12, borderBottom: '2px solid #ddd' }}>Subject</th>
            <th style={{ padding: 12, borderBottom: '2px solid #ddd' }}>Status</th>
            <th style={{ padding: 12, borderBottom: '2px solid #ddd' }}>Priority</th>
            <th style={{ padding: 12, borderBottom: '2px solid #ddd' }}>Updated</th>
          </tr>
        </thead>
        <tbody>
          {tickets.map(ticket => (
            <tr key={ticket.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: 12 }}>#{ticket.id}</td>
              <td style={{ padding: 12 }}>{ticket.subject || '(No subject)'}</td>
              <td style={{ padding: 12 }}>
                <span style={{
                  padding: '4px 8px',
                  borderRadius: 4,
                  fontSize: 12,
                  background: getStatusColor(ticket.status),
                  color: 'white'
                }}>
                  {ticket.status}
                </span>
              </td>
              <td style={{ padding: 12, textTransform: 'capitalize' }}>{ticket.priority || 'normal'}</td>
              <td style={{ padding: 12 }}>{new Date(ticket.updated_at).toLocaleString()}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <div style={{ marginTop: 16 }}>
        <button onClick={loadData} style={{
          padding: '8px 16px',
          background: '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: 4,
          cursor: 'pointer'
        }}>
          Refresh
        </button>
      </div>

      {/* Text fallback */}
      <details style={{ marginTop: 32, padding: 16, background: '#f9f9f9', borderRadius: 4 }}>
        <summary style={{ cursor: 'pointer', fontWeight: 'bold' }}>Text Fallback</summary>
        <pre style={{ marginTop: 12, whiteSpace: 'pre-wrap', fontSize: 12 }}>
          {JSON.stringify({ stats, recent_tickets: tickets }, null, 2)}
        </pre>
      </details>
    </div>
  );
}

function getStatusColor(status: string): string {
  const colors: Record<string, string> = {
    new: '#6c757d',
    open: '#007bff',
    pending: '#ffc107',
    hold: '#fd7e14',
    solved: '#28a745',
    closed: '#343a40',
  };
  return colors[status] || '#6c757d';
}

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