import React, { useState, useMemo, useRef } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { PageHeader } from '../../components/layout/PageHeader';
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 [capFilter, setCapFilter] = useState<string>('all');
  const appRef = useRef<any>(null);

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

  const numbers = useMemo(() => {
    return (data?.availableNumbers || data?.numbers || [])
      .map((n: any) => ({
        number: n.phoneNumber || n.friendlyName || n.number || '',
        friendlyName: n.friendlyName || n.phoneNumber || '',
        locality: n.locality || n.city || '—',
        region: n.region || n.state || '—',
        capabilities: {
          sms: n.capabilities?.sms ?? n.sms ?? false,
          voice: n.capabilities?.voice ?? n.voice ?? false,
          mms: n.capabilities?.mms ?? n.mms ?? false,
        },
        monthlyPrice: n.monthlyPrice ?? n.price ?? '—',
      }))
      .filter((n: any) => {
        if (search && !n.number.includes(search) && !n.locality.toLowerCase().includes(search.toLowerCase())) return false;
        if (capFilter === 'sms' && !n.capabilities.sms) return false;
        if (capFilter === 'voice' && !n.capabilities.voice) return false;
        if (capFilter === 'mms' && !n.capabilities.mms) return false;
        return true;
      });
  }, [data, search, capFilter]);

  const handleProvision = (phoneNumber: string) => {
    if (appRef.current?.sendMessage) {
      appRef.current.sendMessage({ type: 'action', action: 'provision', phoneNumber });
    }
  };

  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>
      <PageHeader title="🔎 Number Hunt" subtitle={`${numbers.length} numbers available`} />
      <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
        <input type="text" className="search-input" placeholder="Search by area code or city…" value={search} onChange={e => setSearch(e.target.value)} style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 4 }}>
          {['all', 'sms', 'voice', 'mms'].map(f => (
            <button key={f} className={`chip ${capFilter === f ? 'chip-active' : ''}`} onClick={() => setCapFilter(f)}>
              {f.toUpperCase()}
            </button>
          ))}
        </div>
      </div>
      <div className="data-table-wrap">
        <div className="table-container">
          <table className="data-table">
            <thead><tr>
              <th>Number</th><th>Location</th><th>Capabilities</th><th>Price/mo</th><th>Action</th>
            </tr></thead>
            <tbody>
              {numbers.map((n: any, i: number) => (
                <tr key={i}>
                  <td style={{ fontFamily: "'SF Mono', monospace", fontWeight: 600 }}>{n.number}</td>
                  <td>{n.locality}, {n.region}</td>
                  <td>
                    {n.capabilities.sms && <span className="tag" style={{ marginRight: 4 }}>SMS</span>}
                    {n.capabilities.voice && <span className="tag" style={{ marginRight: 4, background: 'rgba(34,197,94,0.15)', color: '#4ade80' }}>Voice</span>}
                    {n.capabilities.mms && <span className="tag" style={{ background: 'rgba(245,158,11,0.15)', color: '#fbbf24' }}>MMS</span>}
                  </td>
                  <td>{typeof n.monthlyPrice === 'number' ? `$${n.monthlyPrice.toFixed(2)}` : n.monthlyPrice}</td>
                  <td><button className="btn btn-primary btn-sm" onClick={() => handleProvision(n.number)}>Provision</button></td>
                </tr>
              ))}
              {numbers.length === 0 && <tr><td colSpan={5} style={{ textAlign: 'center', color: '#64748b', padding: 40 }}>No numbers found</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
