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 [severityFilter, setSeverityFilter] = useState<string>('all');

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

  const rows = useMemo(() => {
    return (data?.errors || data?.alerts || [])
      .map((e: any) => {
        const severity = e.severity || e.level || (e.errorCode?.toString().startsWith('3') ? 'warning' : 'error');
        return {
          id: e.id || e.sid || '',
          errorCode: e.errorCode || e.code || '—',
          message: e.message || e.description || '',
          severity,
          resource: e.resource || e.resourceSid || '—',
          timestamp: e.timestamp || e.dateCreated || '',
        };
      })
      .filter((r: any) => {
        if (severityFilter !== 'all' && r.severity !== severityFilter) return false;
        if (!search) return true;
        const q = search.toLowerCase();
        return r.errorCode.toString().includes(q) || r.message.toLowerCase().includes(q) || r.resource.toLowerCase().includes(q);
      });
  }, [data, search, severityFilter]);

  const getSeverityBadge = (severity: string) => {
    const colors: Record<string, { bg: string; color: string }> = {
      error: { bg: 'rgba(239,68,68,0.15)', color: '#f87171' },
      warning: { bg: 'rgba(245,158,11,0.15)', color: '#fbbf24' },
      info: { bg: 'rgba(59,130,246,0.15)', color: '#60a5fa' },
      critical: { bg: 'rgba(239,68,68,0.25)', color: '#ef4444' },
    };
    const c = colors[severity] || colors.info!;
    return <span style={{ padding: '2px 8px', borderRadius: 9999, fontSize: 10, fontWeight: 600, background: c.bg, color: c.color, textTransform: 'uppercase' }}>{severity}</span>;
  };

  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="⚠️ Error Log" subtitle={`${rows.length} error${rows.length !== 1 ? 's' : ''}`}>
      <div style={{ display: 'flex', gap: 8, marginBottom: 12, marginTop: 8 }}>
        <input type="text" className="search-input" placeholder="Search errors…" value={search} onChange={e => setSearch(e.target.value)} style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 4 }}>
          {['all', 'critical', 'error', 'warning', 'info'].map(f => (
            <button key={f} className={`chip ${severityFilter === f ? 'chip-active' : ''}`} onClick={() => setSeverityFilter(f)}>
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </button>
          ))}
        </div>
      </div>
      <div className="data-table-wrap">
        <div className="table-container">
          <table className="data-table">
            <thead><tr>
              <th>Severity</th><th>Code</th><th>Message</th><th>Resource</th><th>Timestamp</th>
            </tr></thead>
            <tbody>
              {rows.map((r: any, i: number) => (
                <tr key={r.id || i}>
                  <td>{getSeverityBadge(r.severity)}</td>
                  <td style={{ fontFamily: "'SF Mono', monospace" }}>{r.errorCode}</td>
                  <td style={{ maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.message}</td>
                  <td style={{ fontFamily: "'SF Mono', monospace", fontSize: 10 }}>{r.resource}</td>
                  <td style={{ fontSize: 11, color: '#64748b' }}>{r.timestamp ? new Date(r.timestamp).toLocaleString() : '—'}</td>
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan={5} style={{ textAlign: 'center', color: '#64748b', padding: 40 }}>No errors found</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </PageHeader>
  );
}
