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 { SplitLayout } from '../../components/layout/SplitLayout';
import { BarChart } from '../../components/charts/BarChart';
import { PieChart } from '../../components/charts/PieChart';
import { DataTable } from '../../components/data/DataTable';
import { ProgressBar } from '../../components/data/ProgressBar';
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: 'Cost Report', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const costs = useMemo(() => {
    if (!data) return null;
    return {
      totalSpend: data.totalSpend ?? data.total ?? 0,
      smsCost: data.smsCost ?? data.messaging ?? 0,
      voiceCost: data.voiceCost ?? data.voice ?? 0,
      numbersCost: data.numbersCost ?? data.phoneNumbers ?? 0,
      otherCost: data.otherCost ?? data.other ?? 0,
      budget: data.budget ?? 0,
    };
  }, [data]);

  const dailySpend = useMemo(() => {
    return (data?.dailySpend || []).map((d: any) => ({
      label: d.date || d.day || '',
      value: d.amount || d.cost || d.value || 0,
    }));
  }, [data]);

  const topItems = useMemo(() => {
    return (data?.topItems || data?.lineItems || []).map((item: any) => ({
      id: item.id || item.category || '',
      category: item.category || item.name || '',
      amount: typeof item.amount === 'number' ? `$${item.amount.toFixed(2)}` : item.amount || '',
      count: item.count || item.usage || '',
    }));
  }, [data]);

  const fmt = (v: number) => `$${v.toFixed(2)}`;

  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="💰 Cost Report" subtitle="Monthly spending breakdown" gradient />
      <StatsGrid columns={4}>
        <MetricCard label="Total Spend" value={fmt(costs!.totalSpend)} color="red" />
        <MetricCard label="SMS" value={fmt(costs!.smsCost)} color="purple" />
        <MetricCard label="Voice" value={fmt(costs!.voiceCost)} color="blue" />
        <MetricCard label="Numbers" value={fmt(costs!.numbersCost)} color="yellow" />
      </StatsGrid>
      {costs!.budget > 0 && (
        <ProgressBar label="Budget vs Actual" value={costs!.totalSpend} max={costs!.budget} color={costs!.totalSpend > costs!.budget ? 'red' : 'green'} benchmarkLabel="Budget" benchmark={costs!.budget} />
      )}
      <SplitLayout ratio="50/50" gap="md">
        <PieChart
          title="Cost by Service"
          segments={[
            { label: 'SMS', value: costs!.smsCost, color: '#8b5cf6' },
            { label: 'Voice', value: costs!.voiceCost, color: '#3b82f6' },
            { label: 'Numbers', value: costs!.numbersCost, color: '#f59e0b' },
            { label: 'Other', value: costs!.otherCost, color: '#64748b' },
          ]}
          donut
        />
        {dailySpend.length > 0 && <BarChart title="Daily Spend" bars={dailySpend} />}
      </SplitLayout>
      {topItems.length > 0 && (
        <DataTable
          columns={[
            { key: 'category', label: 'Category', sortable: true },
            { key: 'amount', label: 'Amount', sortable: true },
            { key: 'count', label: 'Usage', sortable: true },
          ]}
          rows={topItems}
          pageSize={10}
          emptyMessage="No cost items"
        />
      )}
    </div>
  );
}
