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

interface Comment {
  id: number;
  body: string;
  author_id: number;
  public: boolean;
  created_at: string;
}

function App() {
  const app = useApp();
  const [ticketId, setTicketId] = useState('');
  const [ticket, setTicket] = useState<any>(null);
  const [comments, setComments] = useState<Comment[]>([]);
  const [loading, setLoading] = useState(false);

  async function loadTicket() {
    if (!ticketId) return;
    
    try {
      setLoading(true);
      
      const [ticketResult, commentsResult] = await Promise.all([
        app.callTool('zendesk_get_ticket', { ticket_id: parseInt(ticketId) }),
        app.callTool('zendesk_list_ticket_comments', { ticket_id: parseInt(ticketId), sort_order: 'asc' })
      ]);
      
      const ticketData = JSON.parse(ticketResult.content[0].text);
      const commentsData = JSON.parse(commentsResult.content[0].text);
      
      setTicket(ticketData);
      setComments(commentsData.comments || []);
    } catch (error) {
      console.error('Failed to load ticket:', error);
      alert('Failed to load ticket');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ fontFamily: 'system-ui, sans-serif', padding: 20, maxWidth: 1000, margin: '0 auto' }}>
      <h1>Ticket Detail</h1>
      
      <div style={{ marginBottom: 20 }}>
        <input
          type="text"
          placeholder="Enter Ticket ID"
          value={ticketId}
          onChange={e => setTicketId(e.target.value)}
          onKeyPress={e => e.key === 'Enter' && loadTicket()}
          style={{ padding: 8, marginRight: 8, width: 200 }}
        />
        <button onClick={loadTicket} disabled={loading} style={{
          padding: '8px 16px',
          background: '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: 4,
          cursor: 'pointer'
        }}>
          {loading ? 'Loading...' : 'Load Ticket'}
        </button>
      </div>

      {ticket && (
        <div>
          {/* Ticket header */}
          <div style={{ background: '#f8f9fa', padding: 20, borderRadius: 8, marginBottom: 20 }}>
            <h2 style={{ margin: 0, marginBottom: 12 }}>{ticket.subject || '(No subject)'}</h2>
            <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
              <div><strong>ID:</strong> #{ticket.id}</div>
              <div><strong>Status:</strong> <span style={{
                padding: '2px 8px',
                borderRadius: 4,
                background: getStatusColor(ticket.status),
                color: 'white'
              }}>{ticket.status}</span></div>
              <div><strong>Priority:</strong> {ticket.priority || 'normal'}</div>
              <div><strong>Type:</strong> {ticket.type || 'question'}</div>
              <div><strong>Requester:</strong> User #{ticket.requester_id}</div>
              <div><strong>Assignee:</strong> {ticket.assignee_id ? `User #${ticket.assignee_id}` : 'Unassigned'}</div>
            </div>
            {ticket.tags && ticket.tags.length > 0 && (
              <div style={{ marginTop: 12 }}>
                <strong>Tags:</strong> {ticket.tags.map((tag: string) => (
                  <span key={tag} style={{
                    display: 'inline-block',
                    background: '#e9ecef',
                    padding: '2px 8px',
                    borderRadius: 4,
                    marginLeft: 4,
                    fontSize: 12
                  }}>{tag}</span>
                ))}
              </div>
            )}
          </div>

          {/* Comments timeline */}
          <h3>Comments</h3>
          <div style={{ borderLeft: '2px solid #dee2e6', paddingLeft: 20 }}>
            {comments.map((comment, idx) => (
              <div key={comment.id} style={{
                marginBottom: 20,
                padding: 16,
                background: comment.public ? '#fff' : '#fff3cd',
                border: '1px solid ' + (comment.public ? '#dee2e6' : '#ffc107'),
                borderRadius: 4
              }}>
                <div style={{ marginBottom: 8, fontSize: 12, color: '#6c757d' }}>
                  <strong>User #{comment.author_id}</strong> • {new Date(comment.created_at).toLocaleString()} • {comment.public ? 'Public' : 'Internal'}
                </div>
                <div style={{ whiteSpace: 'pre-wrap' }}>{comment.body}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Text fallback */}
      {ticket && (
        <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({ ticket, comments }, 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 />);
