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 SearchTermRow {
  searchTerm: string;
  campaign: string;
  adGroup: string;
  impressions: number;
  clicks: number;
  ctr: number;
  cost: number;
  conversions: number;
  suggestedAction?: 'add_keyword' | 'add_negative' | 'none';
}

interface SearchTermsData {
  period?: string;
  costThreshold?: number;
  terms: SearchTermRow[];
}

/* ─── 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 inferAction(term: SearchTermRow, costThreshold: number): string {
  if (term.suggestedAction && term.suggestedAction !== 'none') return term.suggestedAction;
  if (term.cost > costThreshold && term.conversions === 0) return 'add_negative';
  if (term.conversions > 0 && term.ctr > 0.03) return 'add_keyword';
  return 'none';
}

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

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

  const costThreshold = data?.costThreshold || 5_000_000;

  const filtered = useMemo(() => {
    if (!data) return [];
    return data.terms.filter(t => {
      const action = inferAction(t, costThreshold);
      if (filterAction !== 'ALL' && action !== filterAction) return false;
      if (search && !t.searchTerm.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [data, search, filterAction, costThreshold]);

  const totalCost = useMemo(() => data?.terms.reduce((s, t) => s + t.cost, 0) || 0, [data]);
  const negCandidates = useMemo(() => data?.terms.filter(t => inferAction(t, costThreshold) === 'add_negative').length || 0, [data, costThreshold]);
  const kwCandidates = useMemo(() => data?.terms.filter(t => inferAction(t, costThreshold) === 'add_keyword').length || 0, [data, costThreshold]);

  const tableRows = useMemo(() => {
    return filtered.map((t, i) => {
      const action = inferAction(t, costThreshold);
      const isHighCostLowConv = t.cost > costThreshold && t.conversions === 0;
      return {
        id: String(i),
        searchTerm: t.searchTerm,
        campaign: t.campaign,
        adGroup: t.adGroup,
        impressions: fmtNum(t.impressions),
        clicks: fmtNum(t.clicks),
        ctr: fmtPct(t.ctr),
        cost: fmtMoney(t.cost),
        conversions: fmtNum(t.conversions),
        action,
        _isHighCost: isHighCostLowConv,
      };
    });
  }, [filtered, costThreshold]);

  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 }}>🔍 Search Terms Report</h1>
        <p style={{ fontSize: 13, color: 'var(--gads-text-secondary)', marginTop: 4 }}>
          {data.period ? `${data.period} · ` : ''}{fmtNum(data.terms.length)} search terms · {fmtMoney(totalCost)} total cost
        </p>
      </div>

      {/* KPI Cards */}
      <div className="stats-grid stats-grid-3" style={{ marginBottom: 16 }}>
        <MetricCard label="Search Terms" value={fmtNum(data.terms.length)} color="blue" />
        <MetricCard label="Add as Keyword" value={fmtNum(kwCandidates)} color="green" />
        <MetricCard label="Add as Negative" value={fmtNum(negCandidates)} color="red" />
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap', alignItems: 'center' }}>
        <input
          type="text"
          placeholder="Search terms..."
          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,
          }}
        />
        {[
          { key: 'ALL', label: 'All' },
          { key: 'add_keyword', label: '＋ Keywords' },
          { key: 'add_negative', label: '— Negatives' },
          { key: 'none', label: 'No Action' },
        ].map(f => (
          <button
            key={f.key}
            onClick={() => setFilterAction(f.key)}
            style={{
              padding: '4px 12px', borderRadius: 9999, fontSize: 11, fontWeight: 600,
              border: 'none', cursor: 'pointer',
              background: f.key === filterAction ? 'var(--gads-highlight)' : 'var(--gads-bg-accent)',
              color: f.key === filterAction ? 'white' : 'var(--gads-text-secondary)',
            }}
          >
            {f.label}
          </button>
        ))}
      </div>

      {/* Table with custom rendering for action badges and row highlighting */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table className="data-table" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
            <thead>
              <tr>
                <th style={{ textAlign: 'left', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Search Term</th>
                <th style={{ textAlign: 'left', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Campaign</th>
                <th style={{ textAlign: 'left', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Ad Group</th>
                <th style={{ textAlign: 'right', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Impr.</th>
                <th style={{ textAlign: 'right', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Clicks</th>
                <th style={{ textAlign: 'right', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>CTR</th>
                <th style={{ textAlign: 'right', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Cost</th>
                <th style={{ textAlign: 'right', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Conv.</th>
                <th style={{ textAlign: 'left', padding: '6px 8px', background: 'var(--gads-bg-accent)', color: 'var(--gads-text-secondary)', fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3, borderBottom: '1px solid var(--gads-border)', whiteSpace: 'nowrap' }}>Action</th>
              </tr>
            </thead>
            <tbody>
              {tableRows.length === 0 ? (
                <tr><td colSpan={9} style={{ textAlign: 'center', color: 'var(--gads-text-muted)', padding: 24 }}>No search terms found</td></tr>
              ) : tableRows.map(row => (
                <tr key={row.id} style={{ background: row._isHighCost ? 'var(--gads-red-dim)' : undefined }}>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', fontWeight: 500, maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.searchTerm}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', color: 'var(--gads-text-muted)', maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.campaign}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', color: 'var(--gads-text-muted)', maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.adGroup}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', textAlign: 'right', fontFamily: 'monospace' }}>{row.impressions}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', textAlign: 'right', fontFamily: 'monospace' }}>{row.clicks}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', textAlign: 'right', fontFamily: 'monospace' }}>{row.ctr}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', textAlign: 'right', fontFamily: 'monospace' }}>{row.cost}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)', textAlign: 'right', fontFamily: 'monospace' }}>{row.conversions}</td>
                  <td style={{ padding: '5px 8px', borderBottom: '1px solid var(--gads-border)' }}>
                    {row.action === 'add_keyword' ? (
                      <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 10px', borderRadius: 12, color: 'var(--gads-green)', background: 'var(--gads-green-dim)' }}>＋ Add Keyword</span>
                    ) : row.action === 'add_negative' ? (
                      <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 10px', borderRadius: 12, color: 'var(--gads-red)', background: 'var(--gads-red-dim)' }}>— Add Negative</span>
                    ) : (
                      <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 10px', borderRadius: 12, color: 'var(--gads-text-muted)', background: 'var(--gads-border)' }}>No Action</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Legend */}
      <div style={{ marginTop: 8, fontSize: 11, color: 'var(--gads-text-muted)', display: 'flex', alignItems: 'center', gap: 4 }}>
        <span style={{ display: 'inline-block', width: 12, height: 12, background: 'var(--gads-red-dim)', borderRadius: 2 }} />
        Highlighted rows indicate high-cost terms ({'>'}{fmtMoney(costThreshold)}) with zero conversions
      </div>
    </div>
  );
}
