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 { StatsGrid } from '../../components/layout/StatsGrid';
import { MetricCard } from '../../components/data/MetricCard';
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: 'Batch Validate', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const results = useMemo(() => {
    return (data?.results || []).map((r: any) => ({
      id: r.phone || r.phoneNumber || '',
      phone: r.phone || r.phoneNumber || '',
      valid: r.valid === true ? 'Valid' : r.valid === false ? 'Invalid' : 'Unknown',
      carrier: r.carrier || r.carrierName || '—',
      type: r.type || r.lineType || '—',
      country: r.countryCode || r.country || '—',
    })).filter((r: any) => {
      if (!search) return true;
      return r.phone.includes(search) || r.carrier.toLowerCase().includes(search.toLowerCase());
    });
  }, [data, search]);

  const counts = useMemo(() => {
    const all = data?.results || [];
    return {
      valid: all.filter((r: any) => r.valid === true).length,
      invalid: all.filter((r: any) => r.valid === false).length,
      unknown: all.filter((r: any) => r.valid !== true && r.valid !== false).length,
      total: all.length,
    };
  }, [data]);

  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="✅ Batch Validation" subtitle={`${counts.total} numbers validated`} />
      <StatsGrid columns={3}>
        <MetricCard label="Valid" value={String(counts.valid)} color="green" />
        <MetricCard label="Invalid" value={String(counts.invalid)} color="red" />
        <MetricCard label="Unknown" value={String(counts.unknown)} color="yellow" />
      </StatsGrid>
      <div style={{ marginBottom: 8 }}>
        <input type="text" className="search-input" placeholder="Search phone or carrier…" value={search} onChange={e => setSearch(e.target.value)} style={{ width: '100%' }} />
      </div>
      <DataTable
        columns={[
          { key: 'phone', label: 'Phone Number', sortable: true },
          { key: 'valid', label: 'Valid', format: 'status', sortable: true },
          { key: 'carrier', label: 'Carrier', sortable: true },
          { key: 'type', label: 'Type', sortable: true },
          { key: 'country', label: 'Country', sortable: true },
        ]}
        rows={results}
        pageSize={20}
        emptyMessage="No validation results"
      />
    </div>
  );
}
