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 { ProgressBar } from '../../components/data/ProgressBar';
import { DataTable } from '../../components/data/DataTable';
import { StatusBadge } from '../../components/data/StatusBadge';
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 { isConnected, error } = useApp({
    appInfo: { name: 'Campaign Live', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const stats = useMemo(() => {
    if (!data) return null;
    const sent = data.sent ?? 0;
    const delivered = data.delivered ?? 0;
    const failed = data.failed ?? 0;
    const total = data.total ?? sent + delivered + failed;
    return { sent, delivered, failed, total, name: data.campaignName || data.name || 'SMS Campaign' };
  }, [data]);

  const recipients = useMemo(() => {
    return (data?.recipients || []).map((r: any) => ({
      id: r.id || r.to,
      to: r.to || r.phone || '',
      status: r.status || 'queued',
      deliveredAt: r.deliveredAt || r.timestamp || '—',
      errorCode: r.errorCode || '—',
    }));
  }, [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>;

  const statusVariant = stats!.failed > stats!.delivered ? 'error' : stats!.delivered === stats!.total ? 'complete' : 'active';

  return (
    <div>
      <PageHeader title={`📢 ${stats!.name}`} subtitle="Live campaign tracking" status={statusVariant === 'complete' ? 'COMPLETE' : 'LIVE'} statusVariant={statusVariant} />
      <StatsGrid columns={4}>
        <MetricCard label="Total" value={String(stats!.total)} color="blue" />
        <MetricCard label="Sent" value={String(stats!.sent)} color="purple" />
        <MetricCard label="Delivered" value={String(stats!.delivered)} color="green" />
        <MetricCard label="Failed" value={String(stats!.failed)} color="red" />
      </StatsGrid>
      <ProgressBar label="Delivery Progress" value={stats!.delivered} max={stats!.total || 1} color="green" />
      {stats!.failed > 0 && <ProgressBar label="Failure Rate" value={stats!.failed} max={stats!.total || 1} color="red" />}
      {recipients.length > 0 && (
        <DataTable
          columns={[
            { key: 'to', label: 'Recipient', sortable: true },
            { key: 'status', label: 'Status', format: 'status', sortable: true },
            { key: 'deliveredAt', label: 'Delivered At', format: 'date', sortable: true },
            { key: 'errorCode', label: 'Error Code' },
          ]}
          rows={recipients}
          pageSize={20}
          emptyMessage="No recipients yet"
        />
      )}
    </div>
  );
}
