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 { isConnected, error } = useApp({
    appInfo: { name: 'Number Inventory', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const rows = useMemo(() => {
    return (data?.numbers || data?.phoneNumbers || [])
      .map((n: any) => {
        const caps = n.capabilities || {};
        return {
          id: n.sid || n.phoneNumber || '',
          number: n.phoneNumber || n.number || '',
          friendlyName: n.friendlyName || '—',
          sms: caps.sms || caps.SMS ? '🟢' : '🔴',
          voice: caps.voice || caps.Voice ? '🟢' : '🔴',
          mms: caps.mms || caps.MMS ? '🟢' : '🔴',
          monthlyCost: typeof n.monthlyPrice === 'number' ? `$${n.monthlyPrice.toFixed(2)}` : n.monthlyPrice || '—',
          status: n.status || 'active',
        };
      })
      .filter((r: any) => {
        if (!search) return true;
        const q = search.toLowerCase();
        return r.number.includes(q) || r.friendlyName.toLowerCase().includes(q);
      });
  }, [data, search]);

  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="📱 Number Inventory" subtitle={`${rows.length} active number${rows.length !== 1 ? 's' : ''}`}>
      <div style={{ marginBottom: 8, marginTop: 8 }}>
        <input type="text" className="search-input" placeholder="Search by number or name…" value={search} onChange={e => setSearch(e.target.value)} style={{ width: '100%' }} />
      </div>
      <DataTable
        columns={[
          { key: 'number', label: 'Phone Number', sortable: true },
          { key: 'friendlyName', label: 'Friendly Name', sortable: true },
          { key: 'sms', label: 'SMS' },
          { key: 'voice', label: 'Voice' },
          { key: 'mms', label: 'MMS' },
          { key: 'monthlyCost', label: 'Monthly Cost', sortable: true },
          { key: 'status', label: 'Status', format: 'status', sortable: true },
        ]}
        rows={rows}
        pageSize={20}
        emptyMessage="No phone numbers found"
      />
    </PageHeader>
  );
}
