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

/* ─── Types ──────────────────────────────────────────── */
interface AdGroupRow {
  id: string;
  name: string;
  status: string;
  cpcBid: number;
  impressions: number;
  clicks: number;
  ctr: number;
  cost: number;
  conversions: number;
}

interface CampaignDetailData {
  campaign: {
    id: string;
    name: string;
    status: string;
    channelType: string;
    biddingStrategy: string;
    startDate?: string;
    endDate?: string;
  };
  budget: {
    dailyBudget: number;
    totalSpent: number;
    deliveryMethod?: string;
  };
  metrics: {
    impressions: number;
    clicks: number;
    ctr: number;
    cost: number;
    conversions: number;
    conversionRate: number;
    costPerConversion: number;
    avgCpc: number;
  };
  adGroups: AdGroupRow[];
}

/* ─── 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 getStatusColor(status: string): string {
  const s = status.toUpperCase();
  if (s === 'ENABLED' || s === 'ACTIVE') return 'var(--gads-green)';
  if (s === 'PAUSED') return 'var(--gads-yellow)';
  return 'var(--gads-red)';
}
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)';
  return 'var(--gads-red-dim)';
}

/* ─── MetricRow component ────────────────────────────── */
function MetricRow({ label, value }: { label: string; value: string }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid var(--gads-border)' }}>
      <span style={{ color: 'var(--gads-text-secondary)', fontSize: 13 }}>{label}</span>
      <span style={{ color: 'var(--gads-text-primary)', fontWeight: 600, fontSize: 14, fontFamily: 'monospace' }}>{value}</span>
    </div>
  );
}

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

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

  const adGroupRows = useMemo(() => {
    if (!data) return [];
    return data.adGroups.map(ag => ({
      id: ag.id,
      name: ag.name,
      status: ag.status.toUpperCase(),
      cpcBid: fmtMoney(ag.cpcBid),
      impressions: fmtNum(ag.impressions),
      clicks: fmtNum(ag.clicks),
      ctr: fmtPct(ag.ctr),
      cost: fmtMoney(ag.cost),
      conversions: fmtNum(ag.conversions),
    }));
  }, [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 { campaign: c, budget: b, metrics: m } = data;
  const utilizationPct = b.dailyBudget > 0 ? (b.totalSpent / b.dailyBudget) * 100 : 0;
  const budgetColor = utilizationPct > 95 ? 'var(--gads-red)' : utilizationPct > 70 ? 'var(--gads-yellow)' : 'var(--gads-green)';
  const strategyLabel = c.biddingStrategy.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginBottom: 6 }}>
          <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.3 }}>🔍 {c.name}</h1>
          <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>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', padding: '3px 10px', borderRadius: 12, color: 'var(--gads-blue)', background: 'var(--gads-blue-dim)' }}>
            {c.channelType.replace(/_/g, ' ')}
          </span>
          <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', padding: '3px 10px', borderRadius: 12, color: 'var(--gads-purple)', background: 'var(--gads-purple-dim)' }}>
            {strategyLabel}
          </span>
          {c.startDate && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 10px', borderRadius: 12, color: 'var(--gads-text-muted)', background: 'var(--gads-border)' }}>
              Started {c.startDate}
            </span>
          )}
          {c.endDate && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 10px', borderRadius: 12, color: 'var(--gads-text-muted)', background: 'var(--gads-border)' }}>
              Ends {c.endDate}
            </span>
          )}
        </div>
      </div>

      {/* Budget + Performance side by side */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
        {/* Budget Card */}
        <div className="card">
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>💰 Budget</div>
          <MetricRow label="Daily Budget" value={fmtMoney(b.dailyBudget)} />
          <MetricRow label="Total Spent" value={fmtMoney(b.totalSpent)} />
          {b.deliveryMethod && <MetricRow label="Delivery" value={b.deliveryMethod} />}
          <div style={{ marginTop: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ fontSize: 11, color: 'var(--gads-text-muted)' }}>Utilization</span>
              <span style={{ fontSize: 12, fontFamily: 'monospace' }}>{utilizationPct.toFixed(1)}%</span>
            </div>
            <div style={{ height: 8, background: 'var(--gads-bg-input)', borderRadius: 4, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${Math.min(utilizationPct, 100)}%`, background: budgetColor, borderRadius: 4, transition: 'width 0.3s' }} />
            </div>
          </div>
        </div>

        {/* Performance Card */}
        <div className="card">
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>📊 Performance</div>
          <MetricRow label="Impressions" value={fmtNum(m.impressions)} />
          <MetricRow label="Clicks" value={fmtNum(m.clicks)} />
          <MetricRow label="CTR" value={fmtPct(m.ctr)} />
          <MetricRow label="Cost" value={fmtMoney(m.cost)} />
          <MetricRow label="Avg CPC" value={fmtMoney(m.avgCpc)} />
          <MetricRow label="Conversions" value={fmtNum(m.conversions)} />
          <MetricRow label="Conv. Rate" value={fmtPct(m.conversionRate)} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0' }}>
            <span style={{ color: 'var(--gads-text-secondary)', fontSize: 13 }}>Cost / Conv.</span>
            <span style={{ color: 'var(--gads-text-primary)', fontWeight: 600, fontSize: 14, fontFamily: 'monospace' }}>{fmtMoney(m.costPerConversion)}</span>
          </div>
        </div>
      </div>

      {/* Ad Groups Table */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '16px 18px 0' }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>📂 Ad Groups ({data.adGroups.length})</div>
        </div>
        <DataTable
          columns={[
            { key: 'name', label: 'Ad Group', sortable: true },
            { key: 'status', label: 'Status', sortable: true },
            { key: 'cpcBid', label: 'CPC Bid', sortable: true },
            { key: 'impressions', label: 'Impr.', sortable: true },
            { key: 'clicks', label: 'Clicks', sortable: true },
            { key: 'ctr', label: 'CTR', sortable: true },
            { key: 'cost', label: 'Cost', sortable: true },
            { key: 'conversions', label: 'Conv.', sortable: true },
          ]}
          rows={adGroupRows}
          pageSize={20}
          emptyMessage="No ad groups found"
        />
      </div>
    </div>
  );
}
