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 { DataTable } from '../../components/data/DataTable';
import '../../styles/base.css';
import '../../styles/google-ads-theme.css';

/* ─── Types ──────────────────────────────────────────── */
interface BudgetCampaignRow {
  name: string;
  dailyBudget: number;
  actualSpend: number;
  conversions: number;
  costPerConversion: number;
  roas?: number;
}

interface BudgetSuggestion {
  campaignName: string;
  action: string;
  reason: string;
  estimatedImpact?: string;
}

interface BudgetOptimizerData {
  accountName?: string;
  period?: string;
  totalBudget: number;
  totalSpend: number;
  campaigns: BudgetCampaignRow[];
  suggestions?: BudgetSuggestion[];
}

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

type SpendStatus = 'underspent' | 'on-track' | 'overspent';

function getSpendStatus(budget: number, spend: number): SpendStatus {
  if (budget <= 0) return 'on-track';
  const ratio = spend / budget;
  if (ratio < 0.7) return 'underspent';
  if (ratio > 1.0) return 'overspent';
  return 'on-track';
}

const statusConfig: Record<SpendStatus, { label: string; color: string; bg: string }> = {
  underspent: { label: 'Underspent', color: 'var(--gads-blue)', bg: 'var(--gads-blue-dim)' },
  'on-track': { label: 'On Track', color: 'var(--gads-green)', bg: 'var(--gads-green-dim)' },
  overspent: { label: 'Overspent', color: 'var(--gads-red)', bg: 'var(--gads-red-dim)' },
};

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

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

  const statusCounts = useMemo(() => {
    if (!data) return { underspent: 0, 'on-track': 0, overspent: 0 };
    const counts = { underspent: 0, 'on-track': 0, overspent: 0 };
    data.campaigns.forEach(c => counts[getSpendStatus(c.dailyBudget, c.actualSpend)]++);
    return counts;
  }, [data]);

  const tableRows = useMemo(() => {
    if (!data) return [];
    return data.campaigns.map((c, i) => {
      const status = getSpendStatus(c.dailyBudget, c.actualSpend);
      return {
        id: String(i),
        name: c.name,
        status: statusConfig[status].label,
        budget: fmtMoney(c.dailyBudget),
        spend: fmtMoney(c.actualSpend),
        conversions: fmtNum(c.conversions),
        costPerConv: fmtMoney(c.costPerConversion),
        roas: c.roas !== undefined ? c.roas.toFixed(2) + 'x' : '—',
      };
    });
  }, [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 utilizationPct = data.totalBudget > 0 ? (data.totalSpend / data.totalBudget) * 100 : 0;
  const utilizationColor = utilizationPct > 100 ? 'red' : utilizationPct > 85 ? 'yellow' : 'green';

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

      {/* KPI Cards */}
      <div className="stats-grid stats-grid-4" style={{ marginBottom: 20 }}>
        <MetricCard label="Total Budget" value={fmtMoney(data.totalBudget)} color="blue" />
        <MetricCard label="Total Spend" value={fmtMoney(data.totalSpend)} color="purple" />
        <MetricCard label="Utilization" value={`${utilizationPct.toFixed(1)}%`} color={utilizationColor} />
        <div className="metric-card">
          <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
            <span style={{ fontWeight: 700, color: 'var(--gads-blue)' }}>{statusCounts.underspent}</span>
            <span style={{ fontWeight: 700, color: 'var(--gads-green)' }}>{statusCounts['on-track']}</span>
            <span style={{ fontWeight: 700, color: 'var(--gads-red)' }}>{statusCounts.overspent}</span>
          </div>
          <div className="metric-label">Under / On / Over</div>
        </div>
      </div>

      {/* Budget Allocation Bars */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 16 }}>Budget Allocation</div>
        {data.campaigns.map((c, i) => {
          const status = getSpendStatus(c.dailyBudget, c.actualSpend);
          const spendPct = c.dailyBudget > 0 ? (c.actualSpend / c.dailyBudget) * 100 : 0;
          const cfg = statusConfig[status];
          return (
            <div key={i} style={{ marginBottom: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, fontSize: 13 }}>
                <span style={{ fontWeight: 500 }}>{c.name}</span>
                <span style={{ fontSize: 9, fontWeight: 700, textTransform: 'uppercase', padding: '2px 8px', borderRadius: 12, color: cfg.color, background: cfg.bg }}>
                  {cfg.label}
                </span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ flex: 1, height: 14, background: 'var(--gads-bg-input)', borderRadius: 7, overflow: 'hidden', position: 'relative' }}>
                  <div style={{ position: 'absolute', inset: 0, background: 'var(--gads-border)', borderRadius: 7 }} />
                  <div style={{
                    position: 'absolute', top: 0, left: 0, bottom: 0, borderRadius: 7,
                    width: `${Math.min(spendPct, 100)}%`,
                    background: cfg.color, transition: 'width 0.3s',
                  }} />
                </div>
                <div style={{ fontSize: 12, whiteSpace: 'nowrap', minWidth: 140, fontFamily: 'monospace' }}>
                  <span>{fmtMoney(c.actualSpend)}</span>
                  <span style={{ color: 'var(--gads-text-muted)' }}> / {fmtMoney(c.dailyBudget)}</span>
                </div>
              </div>
            </div>
          );
        })}
        {/* Legend */}
        <div style={{ display: 'flex', gap: 16, marginTop: 16, fontSize: 11 }}>
          {(['underspent', 'on-track', 'overspent'] as SpendStatus[]).map(s => (
            <span key={s} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
              <span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: 2, background: statusConfig[s].color }} />
              {statusConfig[s].label}
            </span>
          ))}
        </div>
      </div>

      {/* Campaign Breakdown Table */}
      <div className="card" style={{ padding: 0, overflow: 'hidden', marginBottom: 20 }}>
        <div style={{ padding: '16px 18px 0' }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Campaign Breakdown</div>
        </div>
        <DataTable
          columns={[
            { key: 'name', label: 'Campaign', sortable: true },
            { key: 'status', label: 'Status', sortable: true },
            { key: 'budget', label: 'Budget', sortable: true },
            { key: 'spend', label: 'Spend', sortable: true },
            { key: 'conversions', label: 'Conv.', sortable: true },
            { key: 'costPerConv', label: 'Cost/Conv', sortable: true },
            { key: 'roas', label: 'ROAS', sortable: true },
          ]}
          rows={tableRows}
          pageSize={20}
          emptyMessage="No campaigns found"
        />
      </div>

      {/* Suggestions */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>🔄 Reallocation Suggestions</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 12 }}>
          {data.suggestions && data.suggestions.length > 0 ? data.suggestions.map((s, i) => (
            <div key={i} className="card" style={{ borderLeft: '3px solid var(--gads-highlight)' }}>
              <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4 }}>📂 {s.campaignName}</div>
              <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>{s.action}</div>
              <div style={{ fontSize: 12, color: 'var(--gads-text-secondary)' }}>{s.reason}</div>
              {s.estimatedImpact && (
                <div style={{ marginTop: 8 }}>
                  <span style={{
                    fontSize: 11, fontWeight: 700, padding: '3px 10px', borderRadius: 12,
                    color: 'var(--gads-green)', background: 'var(--gads-green-dim)',
                  }}>
                    ⬆ {s.estimatedImpact}
                  </span>
                </div>
              )}
            </div>
          )) : (
            <div className="card" style={{ textAlign: 'center', color: 'var(--gads-text-muted)', padding: 24 }}>
              No reallocation suggestions at this time
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
