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 KeywordRow {
  keyword: string;
  matchType: string;
  status: string;
  qualityScore: number;
  clicks: number;
  impressions: number;
  ctr: number;
  cpc: number;
  conversions: number;
}

interface KeywordAnalyzerData {
  campaignName?: string;
  adGroupName?: string;
  keywords: KeywordRow[];
}

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

/* ─── Quality Score Badge ────────────────────────────── */
function QualityScoreBadge({ score }: { score: number }) {
  const clamped = Math.max(0, Math.min(10, score));
  const pct = clamped * 10;
  let color: string, bgColor: string;
  if (clamped >= 7) { color = 'var(--gads-green)'; bgColor = 'var(--gads-green-dim)'; }
  else if (clamped >= 4) { color = 'var(--gads-yellow)'; bgColor = 'var(--gads-yellow-dim)'; }
  else { color = 'var(--gads-red)'; bgColor = 'var(--gads-red-dim)'; }

  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 100 }}>
      <div style={{ flex: 1, height: 6, background: 'var(--gads-bg-input)', borderRadius: 3, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${pct}%`, background: color, borderRadius: 3 }} />
      </div>
      <span style={{ fontSize: 12, fontWeight: 700, fontFamily: 'monospace', color, minWidth: 18, textAlign: 'right' }}>{clamped}</span>
    </div>
  );
}

/* ─── Match Type Badge ───────────────────────────────── */
function MatchTypeBadge({ matchType }: { matchType: string }) {
  const mt = matchType.toUpperCase();
  const colors: Record<string, { c: string; bg: string }> = {
    BROAD: { c: 'var(--gads-blue)', bg: 'var(--gads-blue-dim)' },
    PHRASE: { c: 'var(--gads-purple)', bg: 'var(--gads-purple-dim)' },
    EXACT: { c: 'var(--gads-green)', bg: 'var(--gads-green-dim)' },
  };
  const { c, bg } = colors[mt] || { c: 'var(--gads-text-muted)', bg: 'var(--gads-border)' };
  return (
    <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, padding: '3px 10px', borderRadius: 12, color: c, background: bg }}>
      {mt}
    </span>
  );
}

/* ─── App ────────────────────────────────────────────── */
export function App() {
  const [data, setData] = useState<KeywordAnalyzerData | null>((window as any).__MCP_APP_DATA__ || null);
  const [search, setSearch] = useState('');
  const [filterMatch, setFilterMatch] = useState<string>('ALL');

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

  const filtered = useMemo(() => {
    if (!data) return [];
    return data.keywords.filter(k => {
      if (filterMatch !== 'ALL' && k.matchType.toUpperCase() !== filterMatch) return false;
      if (search && !k.keyword.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [data, search, filterMatch]);

  const avgQS = useMemo(() => {
    if (!filtered.length) return 0;
    return filtered.reduce((s, k) => s + k.qualityScore, 0) / filtered.length;
  }, [filtered]);

  const topPerformer = useMemo(() => {
    if (!filtered.length) return null;
    return [...filtered].sort((a, b) => b.conversions - a.conversions)[0];
  }, [filtered]);

  const tableRows = useMemo(() => {
    return filtered.map((k, i) => ({
      id: String(i),
      keyword: k.keyword,
      matchType: k.matchType,
      status: k.status,
      qualityScore: k.qualityScore,
      clicks: fmtNum(k.clicks),
      impressions: fmtNum(k.impressions),
      ctr: fmtPct(k.ctr),
      cpc: fmtMoney(k.cpc),
      conversions: fmtNum(k.conversions),
    }));
  }, [filtered]);

  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 avgQSColor = avgQS >= 7 ? 'green' : avgQS >= 4 ? 'yellow' : 'red';

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.3 }}>🔑 Keyword Analyzer</h1>
        <p style={{ fontSize: 13, color: 'var(--gads-text-secondary)', marginTop: 4 }}>
          {data.campaignName || 'All campaigns'}{data.adGroupName ? ` → ${data.adGroupName}` : ''}
        </p>
      </div>

      {/* KPI Cards */}
      <div className="stats-grid stats-grid-3" style={{ marginBottom: 16 }}>
        <MetricCard label="Total Keywords" value={fmtNum(filtered.length)} color="blue" />
        <MetricCard label="Avg Quality Score" value={avgQS.toFixed(1)} color={avgQSColor} />
        <MetricCard
          label="Top Performer"
          value={topPerformer ? topPerformer.keyword : '—'}
          color="green"
          trend={topPerformer ? 'up' : undefined}
          trendValue={topPerformer ? `${fmtNum(topPerformer.conversions)} conv` : undefined}
        />
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap', alignItems: 'center' }}>
        <input
          type="text"
          placeholder="Search keywords..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{
            padding: '6px 12px', borderRadius: 6, border: '1px solid var(--gads-border-light)',
            background: 'var(--gads-bg-input)', color: 'var(--gads-text-primary)', fontSize: 12,
            outline: 'none', flex: '1 1 200px', minWidth: 150,
          }}
        />
        {['ALL', 'BROAD', 'PHRASE', 'EXACT'].map(mt => (
          <button
            key={mt}
            onClick={() => setFilterMatch(mt)}
            style={{
              padding: '4px 12px', borderRadius: 9999, fontSize: 11, fontWeight: 600,
              border: 'none', cursor: 'pointer',
              background: mt === filterMatch ? 'var(--gads-highlight)' : 'var(--gads-bg-accent)',
              color: mt === filterMatch ? 'white' : 'var(--gads-text-secondary)',
            }}
          >
            {mt}
          </button>
        ))}
      </div>

      {/* Table */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <DataTable
          columns={[
            { key: 'keyword', label: 'Keyword', sortable: true },
            { key: 'matchType', label: 'Match Type', sortable: true },
            { key: 'status', label: 'Status', sortable: true },
            { key: 'qualityScore', label: 'Quality Score', sortable: true, width: '130px' },
            { key: 'clicks', label: 'Clicks', sortable: true },
            { key: 'impressions', label: 'Impr.', sortable: true },
            { key: 'ctr', label: 'CTR', sortable: true },
            { key: 'cpc', label: 'CPC', sortable: true },
            { key: 'conversions', label: 'Conv.', sortable: true },
          ]}
          rows={tableRows}
          pageSize={20}
          emptyMessage="No keywords found"
        />
      </div>
    </div>
  );
}
