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

  const metrics = useMemo(() => {
    if (!data) return null;
    return {
      balance: data.balance ?? data.accountBalance ?? '$0.00',
      activeNumbers: data.activeNumbers ?? data.phoneNumbers?.length ?? 0,
      messagesSent: data.messagesSent ?? data.messages?.sent ?? 0,
      messagesReceived: data.messagesReceived ?? data.messages?.received ?? 0,
      callsTotal: data.callsTotal ?? data.calls?.total ?? 0,
      callMinutes: data.callMinutes ?? data.calls?.minutes ?? 0,
    };
  }, [data]);

  const recentActivity = useMemo(() => {
    if (!data?.recentActivity) return [];
    return (data.recentActivity || []).map((a: any) => ({
      title: a.title || a.type || 'Activity',
      description: a.description || a.details || '',
      timestamp: a.timestamp || a.date || '',
      variant: a.variant || (a.type === 'error' ? 'error' : 'default'),
      icon: a.icon || (a.type === 'sms' ? 'sms' : a.type === 'call' ? 'call' : 'system'),
    }));
  }, [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="📊 Twilio Dashboard" subtitle="Account overview and recent activity" gradient />
      <StatsGrid columns={3}>
        <MetricCard label="Account Balance" value={typeof metrics!.balance === 'number' ? `$${metrics!.balance.toFixed(2)}` : String(metrics!.balance)} color="green" />
        <MetricCard label="Active Numbers" value={String(metrics!.activeNumbers)} color="blue" />
        <MetricCard label="Messages Sent" value={Number(metrics!.messagesSent).toLocaleString()} color="purple" />
        <MetricCard label="Messages Received" value={Number(metrics!.messagesReceived).toLocaleString()} color="blue" />
        <MetricCard label="Total Calls" value={Number(metrics!.callsTotal).toLocaleString()} color="yellow" />
        <MetricCard label="Call Minutes" value={Number(metrics!.callMinutes).toLocaleString()} color="red" />
      </StatsGrid>
      {recentActivity.length > 0 && (
        <Card title="Recent Activity">
          <Timeline events={recentActivity} />
        </Card>
      )}
    </div>
  );
}
