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 [selectedId, setSelectedId] = useState<string | null>(null);

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

  const conversations = useMemo(() => {
    return (data?.conversations || []).map((c: any) => ({
      id: c.id || c.sid || c.conversationSid || '',
      name: c.name || c.friendlyName || c.from || 'Unknown',
      lastMessage: c.lastMessage || c.preview || c.body || '',
      channel: c.channel || c.type || 'sms',
      timestamp: c.timestamp || c.dateUpdated || '',
      unread: c.unread ?? c.unreadCount ?? 0,
      messages: c.messages || [],
    }));
  }, [data]);

  const selected = conversations.find((c: any) => c.id === selectedId) || conversations[0] || null;
  const messages = selected?.messages || [];

  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>;

  const channelBadge = (ch: string) => {
    const c = ch.toLowerCase();
    if (c.includes('whatsapp')) return <span className="inbox-channel-badge badge-whatsapp">WhatsApp</span>;
    if (c.includes('chat') || c.includes('web')) return <span className="inbox-channel-badge badge-chat">Chat</span>;
    return <span className="inbox-channel-badge badge-sms">SMS</span>;
  };

  return (
    <div className="inbox-layout">
      {/* Sidebar */}
      <div className="inbox-sidebar">
        <div style={{ padding: '12px 14px', borderBottom: '1px solid #2a2d3a' }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0' }}>📥 Inbox</div>
          <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>{conversations.length} conversations</div>
        </div>
        {conversations.map((c: any) => (
          <div
            key={c.id}
            className={`inbox-item ${(selected?.id === c.id) ? 'inbox-item-active' : ''}`}
            onClick={() => setSelectedId(c.id)}
          >
            <div className="inbox-item-name">
              {c.name}
              {c.unread > 0 && <span style={{ marginLeft: 6, background: '#6366f1', color: 'white', borderRadius: 9999, padding: '1px 6px', fontSize: 10, fontWeight: 700 }}>{c.unread}</span>}
            </div>
            <div className="inbox-item-preview">{c.lastMessage}</div>
            <div className="inbox-item-meta">
              {channelBadge(c.channel)}
              <span className="inbox-item-time">{c.timestamp ? new Date(c.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}</span>
            </div>
          </div>
        ))}
        {conversations.length === 0 && <div style={{ padding: 20, textAlign: 'center', color: '#64748b', fontSize: 12 }}>No conversations</div>}
      </div>

      {/* Main area */}
      <div className="inbox-main">
        {selected ? (
          <div className="chat-thread" style={{ border: 'none', background: 'transparent' }}>
            <div className="chat-thread-header" style={{ background: '#1a1d27', borderRadius: 8, marginBottom: 12 }}>
              <div>
                <div className="chat-thread-title">{selected.name}</div>
                <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>{channelBadge(selected.channel)}</div>
              </div>
              <span className="chat-thread-count">{messages.length} messages</span>
            </div>
            <div className="chat-thread-body" style={{ maxHeight: 'calc(100vh - 140px)' }}>
              {messages.map((msg: any, i: number) => {
                const isOutbound = msg.direction === 'outbound' || msg.direction === 'outbound-api' || msg.author === 'agent';
                return (
                  <div key={i} className={`chat-msg ${isOutbound ? 'chat-msg-outbound' : 'chat-msg-inbound'}`}>
                    <div className={`chat-bubble-wrap ${isOutbound ? 'chat-bubble-wrap-right' : ''}`}>
                      <div className={`chat-bubble ${isOutbound ? 'chat-bubble-outbound' : 'chat-bubble-inbound'}`}>
                        {msg.body || msg.text || msg.content || ''}
                      </div>
                      <div className="chat-meta">{msg.timestamp ? new Date(msg.timestamp).toLocaleString() : ''}</div>
                    </div>
                  </div>
                );
              })}
              {messages.length === 0 && <div style={{ textAlign: 'center', color: '#64748b', padding: 40 }}>No messages in this conversation</div>}
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: '#64748b' }}>
            Select a conversation
          </div>
        )}
      </div>
    </div>
  );
}
