import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { PageHeader } from '../../components/layout/PageHeader';
import { DataTable } from '../../components/data/DataTable';
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 [search, setSearch] = useState('');
  const [dirFilter, setDirFilter] = useState<string>('all');

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

  const rows = useMemo(() => {
    const messages: any[] = data?.messages || [];
    return messages
      .map((m) => ({
        id: m.sid || m.id || '',
        from: m.from || '',
        to: m.to || '',
        body: (m.body || '').slice(0, 80) + ((m.body || '').length > 80 ? '…' : ''),
        status: m.status || 'unknown',
        direction: m.direction || 'unknown',
        date: m.dateSent || m.dateCreated || '',
        price: m.price ? `$${Math.abs(parseFloat(m.price)).toFixed(4)}` : '—',
      }))
      .filter((r) => {
        if (dirFilter !== 'all' && !r.direction.includes(dirFilter)) return false;
        if (!search) return true;
        const q = search.toLowerCase();
        return r.from.includes(q) || r.to.includes(q) || r.body.toLowerCase().includes(q);
      });
  }, [data, search, dirFilter]);

  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 (
    <PageHeader title="📨 Message Log" subtitle={`${rows.length} message${rows.length !== 1 ? 's' : ''}`}>
      <div style={{ display: 'flex', gap: 8, marginBottom: 12, marginTop: 8 }}>
        <input
          type="text"
          className="search-input"
          placeholder="Search by phone or message body…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          style={{ flex: 1 }}
        />
        <div className="filter-chips" style={{ padding: 0, border: 'none' }}>
          {['all', 'inbound', 'outbound'].map(f => (
            <button key={f} className={`chip ${dirFilter === f ? 'chip-active' : ''}`} onClick={() => setDirFilter(f)}>
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </button>
          ))}
        </div>
      </div>
      <DataTable
        columns={[
          { key: 'direction', label: 'Dir', sortable: true },
          { key: 'from', label: 'From', sortable: true },
          { key: 'to', label: 'To', sortable: true },
          { key: 'body', label: 'Body' },
          { key: 'status', label: 'Status', format: 'status', sortable: true },
          { key: 'date', label: 'Date', format: 'date', sortable: true },
          { key: 'price', label: 'Cost' },
        ]}
        rows={rows}
        pageSize={25}
        emptyMessage="No messages found"
      />
    </PageHeader>
  );
}
