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

/* ─── Types (from campaign-dashboard.ts) ─────────────── */
interface CampaignCard {
  id: string;
  name: string;
  status: string;
  channelType: string;
  spend: number;
  clicks: number;
  impressions: number;
  ctr: number;
  conversions: number;
  dailyBudget: number;
}

interface CampaignDashboardData {
  accountName?: string;
  campaigns: CampaignCard[];
  sortBy?: 'spend' | 'conversions' | 'ctr';
}

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

const channelColors: Record<string, string> = {
  SEARCH: '#4ea8de', DISPLAY: '#9b5de5', SHOPPING: '#f48c06',
  VIDEO: '#e94560', 'PERFORMANCE MAX': '#00c897', 'PERFORMANCE_MAX': '#00c897',
  DISCOVERY: '#f0c040', LOCAL: '#6c6c8a', SMART: '#6c6c8a',
};

function getChannelColor(ch: string): string {
  return channelColors[ch.toUpperCase().replace(/_/g, ' ')] || channelColors[ch.toUpperCase()] || '#6c6c8a';
}

function getStatusColor(status: string): string {
  const s = status.toUpperCase();
  if (s === 'ENABLED' || s === 'ACTIVE') return 'var(--gads-green)';
  if (s === 'PAUSED') return 'var(--gads-yellow)';
  if (s === 'REMOVED' || s === 'DISABLED') return 'var(--gads-red)';
  return 'var(--gads-text-muted)';
}

function getStatusBg(status: string): string {
  const s = status.toUpperCase();
  if (s === 'ENABLED' || s === 'ACTIVE') return 'var(--gads-green-dim)';
  if (s === 'PAUSED') return 'var(--gads-yellow-dim)';
  if (s === 'REMOVED' || s === 'DISABLED') return 'var(--gads-red-dim)';
  return 'var(--gads-border)';
}

/* ─── App ────────────────────────────────────────────── */
export function App() {
  const [data, setData] = useState<CampaignDashboardData | null>((window as any).__MCP_APP_DATA__ || null);
  const [sortBy, setSortBy] = useState<'spend' | 'conversions' | 'ctr'>('spend');

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

  const sorted = useMemo(() => {
    if (!data) return [];
    const campaigns = [...data.campaigns];
    switch (sortBy) {
      case 'conversions': return campaigns.sort((a, b) => b.conversions - a.conversions);
      case 'ctr': return campaigns.sort((a, b) => b.ctr - a.ctr);
      default: return campaigns.sort((a, b) => b.spend - a.spend);
    }
  }, [data, sortBy]);

  const totalSpend = useMemo(() => data?.campaigns.reduce((s, c) => s + c.spend, 0) || 0, [data]);
  const totalConv = useMemo(() => data?.campaigns.reduce((s, c) => s + c.conversions, 0) || 0, [data]);
  const totalClicks = useMemo(() => data?.campaigns.reduce((s, c) => s + c.clicks, 0) || 0, [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 style={{ maxWidth: 1200, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.3 }}>📊 Campaign Dashboard</h1>
        <p style={{ fontSize: 13, color: 'var(--gads-text-secondary)', marginTop: 4 }}>
          {data.accountName ? `${data.accountName} — ` : ''}{sorted.length} campaigns · {fmtMoney(totalSpend)} total spend · {fmtNum(totalConv)} conversions
        </p>
      </div>

      {/* KPI Cards */}
      <div className="stats-grid stats-grid-4" style={{ marginBottom: 16 }}>
        <MetricCard label="Total Spend" value={fmtMoney(totalSpend)} color="red" />
        <MetricCard label="Conversions" value={fmtNum(totalConv)} color="green" />
        <MetricCard label="Total Clicks" value={fmtNum(totalClicks)} color="blue" />
        <MetricCard label="Campaigns" value={String(sorted.length)} color="purple" />
      </div>

      {/* Sort Controls */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, alignItems: 'center' }}>
        <span style={{ fontSize: 12, color: 'var(--gads-text-muted)' }}>Sort by:</span>
        {(['spend', 'conversions', 'ctr'] as const).map(s => (
          <button
            key={s}
            onClick={() => setSortBy(s)}
            style={{
              padding: '3px 10px', borderRadius: 12, fontSize: 10, fontWeight: 700,
              textTransform: 'uppercase', letterSpacing: 0.5, border: 'none', cursor: 'pointer',
              background: s === sortBy ? 'var(--gads-highlight-dim)' : 'var(--gads-border)',
              color: s === sortBy ? 'var(--gads-highlight)' : 'var(--gads-text-muted)',
            }}
          >
            {s}
          </button>
        ))}
      </div>

      {/* Campaign Cards Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
        {sorted.map(c => {
          const budgetPct = c.dailyBudget > 0 ? (c.spend / c.dailyBudget) * 100 : 0;
          const budgetColor = budgetPct > 95 ? 'var(--gads-red)' : budgetPct > 70 ? 'var(--gads-yellow)' : 'var(--gads-green)';
          const channelLabel = c.channelType.toUpperCase().replace(/_/g, ' ');

          return (
            <div key={c.id} className="card" style={{ display: 'flex', flexDirection: 'column', padding: 20 }}>
              {/* Name + Status */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <span style={{ fontWeight: 600, fontSize: 14 }}>{c.name}</span>
                <span style={{
                  fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5,
                  padding: '3px 10px', borderRadius: 12,
                  color: getStatusColor(c.status), background: getStatusBg(c.status),
                }}>
                  {c.status.toUpperCase()}
                </span>
              </div>

              {/* Channel Badge */}
              <div style={{ marginBottom: 12 }}>
                <span style={{
                  fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5,
                  padding: '3px 10px', borderRadius: 12,
                  color: getChannelColor(c.channelType),
                  background: getChannelColor(c.channelType) + '26',
                }}>
                  {channelLabel}
                </span>
              </div>

              {/* Metrics Grid */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 12 }}>
                <div>
                  <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: 'var(--gads-text-muted)' }}>Spend</div>
                  <div style={{ fontSize: 15, fontWeight: 700, fontFamily: 'var(--mono, monospace)' }}>{fmtMoney(c.spend)}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: 'var(--gads-text-muted)' }}>Conversions</div>
                  <div style={{ fontSize: 15, fontWeight: 700, fontFamily: 'var(--mono, monospace)' }}>{fmtNum(c.conversions)}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: 'var(--gads-text-muted)' }}>Clicks</div>
                  <div style={{ fontSize: 14, fontFamily: 'var(--mono, monospace)' }}>{fmtNum(c.clicks)}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: 'var(--gads-text-muted)' }}>CTR</div>
                  <div style={{ fontSize: 14, fontFamily: 'var(--mono, monospace)' }}>{fmtPct(c.ctr)}</div>
                </div>
                <div style={{ gridColumn: 'span 2' }}>
                  <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: 'var(--gads-text-muted)' }}>Impressions</div>
                  <div style={{ fontSize: 14, fontFamily: 'var(--mono, monospace)' }}>{fmtNum(c.impressions)}</div>
                </div>
              </div>

              {/* Budget Utilization */}
              <div style={{ marginTop: 'auto' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontSize: 10, color: 'var(--gads-text-muted)' }}>Budget Utilization</span>
                  <span style={{ fontSize: 11, fontFamily: 'var(--mono, monospace)' }}>{budgetPct.toFixed(0)}%</span>
                </div>
                <div style={{ height: 8, background: 'var(--gads-bg-input)', borderRadius: 4, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${Math.min(budgetPct, 100)}%`, background: budgetColor, borderRadius: 4, transition: 'width 0.3s' }} />
                </div>
                <div style={{ fontSize: 10, color: 'var(--gads-text-muted)', marginTop: 4 }}>
                  {fmtMoney(c.spend)} / {fmtMoney(c.dailyBudget)} daily
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
