import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { MetricCard } from '../../components/data/MetricCard';
import { BarChart } from '../../components/charts/BarChart';
import { DataTable } from '../../components/data/DataTable';
import '../../styles/base.css';
import '../../styles/google-ads-theme.css';

/* ─── Types ──────────────────────────────────────────── */
interface DailySpendPoint { date: string; spend: number; }
interface TopCampaign { name: string; spend: number; conversions: number; ctr: number; roas?: number; }

interface PerformanceOverviewData {
  accountName?: string;
  period: string;
  kpis: {
    totalSpend: number;
    clicks: number;
    impressions: number;
    ctr: number;
    avgCpc: number;
    conversions: number;
  };
  previousKpis?: {
    totalSpend: number;
    clicks: number;
    impressions: number;
    ctr: number;
    avgCpc: number;
    conversions: number;
  };
  dailySpend: DailySpendPoint[];
  topCampaigns: TopCampaign[];
}

/* ─── Helpers ────────────────────────────────────────── */
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;
}

function fmtMoney(micros: number): string {
  return '$' + (micros / 1_000_000).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function fmtNum(v: number): string { return v.toLocaleString('en-US'); }
function fmtPct(v: number): string { return (v * 100).toFixed(2) + '%'; }

function getDelta(current: number, previous?: number): { arrow: string; cls: string; value: string } | null {
  if (previous === undefined || previous === 0) return null;
  const pct = ((current - previous) / Math.abs(previous)) * 100;
  return {
    arrow: pct >= 0 ? '↑' : '↓',
    cls: pct >= 0 ? 'up' : 'down',
    value: `${Math.abs(pct).toFixed(1)}%`,
  };
}

/* ─── App ────────────────────────────────────────────── */
export function App() {
  const [data, setData] = useState<PerformanceOverviewData | null>((window as any).__MCP_APP_DATA__ || null);

  const { isConnected, error } = useApp({
    appInfo: { name: 'Performance Overview', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const topCampaignRows = useMemo(() => {
    if (!data) return [];
    return data.topCampaigns.map((c, i) => ({
      id: String(i),
      rank: i + 1,
      name: c.name,
      spend: fmtMoney(c.spend),
      conversions: fmtNum(c.conversions),
      ctr: fmtPct(c.ctr),
      roas: c.roas !== undefined ? c.roas.toFixed(2) + 'x' : '—',
    }));
  }, [data]);

  const dailyBars = useMemo(() => {
    if (!data) return [];
    return data.dailySpend.map(d => ({
      label: d.date.length > 5 ? d.date.slice(-5) : d.date,
      value: d.spend / 1_000_000,
      color: '#e94560',
    }));
  }, [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 k = data.kpis;
  const p = data.previousKpis;

  const kpiItems: { label: string; value: string; current: number; previous?: number; color: 'red' | 'blue' | 'purple' | 'green' | 'yellow' }[] = [
    { label: 'Total Spend', value: fmtMoney(k.totalSpend), current: k.totalSpend, previous: p?.totalSpend, color: 'red' },
    { label: 'Clicks', value: fmtNum(k.clicks), current: k.clicks, previous: p?.clicks, color: 'blue' },
    { label: 'Impressions', value: fmtNum(k.impressions), current: k.impressions, previous: p?.impressions, color: 'purple' },
    { label: 'CTR', value: fmtPct(k.ctr), current: k.ctr, previous: p?.ctr, color: 'green' },
    { label: 'Avg CPC', value: fmtMoney(k.avgCpc), current: k.avgCpc, previous: p?.avgCpc, color: 'yellow' },
    { label: 'Conversions', value: fmtNum(k.conversions), current: k.conversions, previous: p?.conversions, color: 'green' },
  ];

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.3 }}>📈 Performance Overview</h1>
        <p style={{ fontSize: 13, color: 'var(--gads-text-secondary)', marginTop: 4 }}>
          {data.accountName ? `${data.accountName} · ` : ''}{data.period}
        </p>
      </div>

      {/* KPI Cards */}
      <div className="stats-grid stats-grid-6" style={{ marginBottom: 20 }}>
        {kpiItems.map((item, i) => {
          const delta = getDelta(item.current, item.previous);
          return (
            <MetricCard
              key={i}
              label={item.label}
              value={item.value}
              color={item.color}
              trend={delta ? (delta.cls === 'up' ? 'up' : 'down') : undefined}
              trendValue={delta ? `${delta.arrow} ${delta.value}` : undefined}
            />
          );
        })}
      </div>

      {/* Daily Spend Chart */}
      <div style={{ marginBottom: 20 }}>
        <BarChart
          title="Daily Spend — Last 7 Days"
          bars={dailyBars}
          orientation="vertical"
          showValues={true}
        />
      </div>

      {/* Top Campaigns Table */}
      <div style={{ marginBottom: 20 }}>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '16px 18px 0' }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Top Campaigns</div>
          </div>
          <DataTable
            columns={[
              { key: 'rank', label: '#', width: '40px' },
              { key: 'name', label: 'Campaign', sortable: true },
              { key: 'spend', label: 'Spend', sortable: true },
              { key: 'conversions', label: 'Conv.', sortable: true },
              { key: 'ctr', label: 'CTR', sortable: true },
              { key: 'roas', label: 'ROAS', sortable: true },
            ]}
            rows={topCampaignRows}
            pageSize={10}
            emptyMessage="No campaigns found"
          />
        </div>
      </div>
    </div>
  );
}
