import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import '../../styles/base.css';
import '../../styles/interactive.css';

function extractData(result: CallToolResult): any {
  const sc = (result as any).structuredContent;
  if (sc) return sc;
  for (const item of result.content || []) {
    if (item.type === 'text') { try { return JSON.parse(item.text); } catch {} }
  }
  return null;
}

export function App() {
  const [data, setData] = useState<any>((window as any).__MCP_APP_DATA__ || null);

  const { isConnected, error } = useApp({
    appInfo: { name: 'Conversation Thread', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const messages = useMemo(() => {
    return (data?.messages || []).map((m: any) => ({
      id: m.sid || m.id || '',
      body: m.body || m.text || '',
      direction: m.direction || (m.from === data?.myNumber ? 'outbound' : 'inbound'),
      from: m.from || '',
      to: m.to || '',
      status: m.status || '',
      timestamp: m.dateSent || m.dateCreated || m.timestamp || '',
    }));
  }, [data]);

  const contactName = data?.contactName || data?.to || data?.from || 'Conversation';
  const contactNumber = data?.contactNumber || data?.to || '';

  if (error) return <div className="error-state"><h3>Error</h3><p>{error.message}</p></div>;
  if (!isConnected) return <div className="loading-state"><div className="loading-spinner" /><p>Connecting...</p></div>;
  if (!data) return <div className="loading-state"><div className="loading-spinner" /><p>Waiting for data...</p></div>;

  return (
    <div className="chat-thread">
      <div className="chat-thread-header">
        <div>
          <div className="chat-thread-title">💬 {contactName}</div>
          {contactNumber && <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>{contactNumber}</div>}
        </div>
        <span className="chat-thread-count">{messages.length} messages</span>
      </div>
      <div className="chat-thread-body">
        {messages.map((msg: any, i: number) => {
          const isOutbound = msg.direction === 'outbound-api' || msg.direction === 'outbound' || msg.direction === 'outbound-call';
          return (
            <div key={msg.id || i} className={`chat-msg ${isOutbound ? 'chat-msg-outbound' : 'chat-msg-inbound'}`}>
              {!isOutbound && (
                <div className="chat-avatar" style={{ background: '#6366f1' }}>
                  {(contactName || '?')[0].toUpperCase()}
                </div>
              )}
              <div className={`chat-bubble-wrap ${isOutbound ? 'chat-bubble-wrap-right' : ''}`}>
                <div className={`chat-bubble ${isOutbound ? 'chat-bubble-outbound' : 'chat-bubble-inbound'}`}>
                  {msg.body}
                </div>
                <div className="chat-meta">
                  {msg.timestamp && <span>{new Date(msg.timestamp).toLocaleString()}</span>}
                  {msg.status && <span> · {msg.status}</span>}
                </div>
              </div>
              {isOutbound && (
                <div className="chat-avatar" style={{ background: '#22c55e' }}>You</div>
              )}
            </div>
          );
        })}
        {messages.length === 0 && <div style={{ textAlign: 'center', color: '#64748b', padding: 40 }}>No messages yet</div>}
      </div>
    </div>
  );
}
