import React, { useState } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { PageHeader } from '../../components/layout/PageHeader';
import { MetricCard } from '../../components/data/MetricCard';
import { LineChart } from '../../components/charts/LineChart';
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: 'Spend Tracker', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  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 dailyData: any[] = data?.dailyData || [];
  const totalSpend = data?.totalSpend || 0;
  const avgDailySpend = data?.avgDailySpend || 0;
  const dayOverDayChange = data?.dayOverDayChange || 0;
  const projectedEndSpend = data?.projectedEndSpend || 0;
  const budget = data?.budget || {};
  const totalBudget = budget.total || 0;
  const budgetPacing = budget.pacing || 0;
  const pacingStatus = budget.status || (budgetPacing > 110 ? 'over' : budgetPacing < 90 ? 'under' : 'on-track');
  const datePreset = data?.datePreset || 'last_30d';

  const chartPoints = dailyData.map((d: any) => {
    const date = new Date(d.date || d.date_start);
    return { label: `${date.getMonth() + 1}/${date.getDate()}`, value: parseFloat(d.spend || 0) };
  });

  return (
    <PageHeader title="💰 Spend Tracker" subtitle={datePreset}>
      <LineChart points={chartPoints} color="#e94560" showArea showPoints title={`Daily Spend (${datePreset})`} yAxisLabel="Spend ($)" />

      {totalBudget > 0 && (
        <div className="card" style={{ marginTop: 8, padding: 16 }}>
          <div className="card-title" style={{ marginBottom: 10 }}>Budget Pacing</div>
          <div className="progress-track" style={{ height: 24, borderRadius: 12 }}>
            <div className="bar-red" style={{
              width: `${Math.min(budgetPacing, 100)}%`,
              height: '100%',
              borderRadius: 12,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'flex-end',
              paddingRight: 8,
              fontSize: 11,
              fontWeight: 700,
              color: '#fff',
            }}>
              {budgetPacing.toFixed(1)}%
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#999', marginTop: 6 }}>
            <span>${totalSpend.toFixed(2)} spent</span>
            <span>${totalBudget.toFixed(2)} budget</span>
          </div>
          <div style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 6,
            padding: '6px 14px',
            borderRadius: 20,
            fontWeight: 600,
            fontSize: 12,
            marginTop: 8,
            background: pacingStatus === 'over' ? 'rgba(231,76,60,0.2)' : pacingStatus === 'under' ? 'rgba(243,156,18,0.2)' : 'rgba(39,174,96,0.2)',
            color: pacingStatus === 'over' ? '#e74c3c' : pacingStatus === 'under' ? '#f39c12' : '#27ae60',
          }}>
            {pacingStatus === 'over' ? '⚠️ Overspending' : pacingStatus === 'under' ? '📉 Underspending' : '✅ On Track'}
          </div>
        </div>
      )}

      <div className="stats-grid stats-grid-4" style={{ marginTop: 8 }}>
        <MetricCard label="Total Spend" value={`$${totalSpend.toFixed(2)}`} color="red" />
        <MetricCard label="Avg Daily" value={`$${avgDailySpend.toFixed(2)}`} color="blue" />
        <MetricCard label="Projected" value={`$${projectedEndSpend.toFixed(2)}`} color="purple" />
        <MetricCard
          label="Day-over-Day"
          value={`${dayOverDayChange >= 0 ? '+' : ''}${dayOverDayChange.toFixed(1)}%`}
          color={dayOverDayChange >= 0 ? 'green' : 'red'}
          trend={dayOverDayChange >= 0 ? 'up' : 'down'}
          trendValue={`${Math.abs(dayOverDayChange).toFixed(1)}%`}
        />
      </div>
    </PageHeader>
  );
}
