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

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;
}

export function App() {
  const [data, setData] = useState<any>((window as any).__MCP_APP_DATA__ || null);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');

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

  const ads: any[] = data?.ads || [];
  const totals = data?.totals || {};
  const datePreset = data?.datePreset || 'last_7d';

  const avgCtr = totals.avgCtr || 0;
  const avgCpc = totals.avgCpc || 0;

  const filteredAds = useMemo(() => {
    return ads.filter(a => {
      if (statusFilter !== 'all' && (a.status || '').toLowerCase() !== statusFilter) return false;
      if (search) {
        const q = search.toLowerCase();
        return (a.name || '').toLowerCase().includes(q) || (a.campaignName || '').toLowerCase().includes(q);
      }
      return true;
    });
  }, [ads, statusFilter, search]);

  const rows = useMemo(() => filteredAds.map((a, i) => ({
    id: a.id || String(i),
    name: a.name || 'Unknown',
    campaignName: a.campaignName || a.campaign_name || '—',
    adsetName: a.adsetName || a.adset_name || '—',
    status: a.status || 'UNKNOWN',
    impressions: (a.impressions || 0).toLocaleString(),
    clicks: (a.clicks || 0).toLocaleString(),
    ctr: `${(a.ctr || 0).toFixed(2)}%`,
    spend: `$${(a.spend || 0).toFixed(2)}`,
    cpc: `$${(a.cpc || 0).toFixed(2)}`,
    conversions: a.conversions || 0,
    cpa: a.conversions > 0 ? `$${(a.cpa || 0).toFixed(2)}` : '—',
    roas: a.roas > 0 ? `${(a.roas || 0).toFixed(2)}x` : '—',
    _ctrRaw: a.ctr || 0,
    _cpcRaw: a.cpc || 0,
  })), [filteredAds]);

  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 statuses = ['all', ...Array.from(new Set(ads.map(a => (a.status || '').toLowerCase())))];

  return (
    <PageHeader title="🎯 Ad Performance Grid" subtitle={`${datePreset} · ${ads.length} ads`}>
      <div className="stats-grid stats-grid-4" style={{ marginTop: 8, marginBottom: 8 }}>
        <MetricCard label="Total Spend" value={`$${(totals.totalSpend || 0).toFixed(2)}`} color="red" />
        <MetricCard label="Avg CTR" value={`${avgCtr.toFixed(2)}%`} color="green" />
        <MetricCard label="Avg CPC" value={`$${avgCpc.toFixed(2)}`} color="blue" />
        <MetricCard label="ROAS" value={`${(totals.avgRoas || 0).toFixed(2)}x`} color="purple" />
      </div>

      <div style={{ display: 'flex', gap: 8, marginBottom: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        <input type="text" className="search-input" placeholder="Search ads…" value={search} onChange={e => setSearch(e.target.value)} style={{ flex: 1, minWidth: 200, maxWidth: 400, padding: '6px 10px', fontSize: 12 }} />
        <div className="filter-chips">
          {statuses.map(s => (
            <button key={s} className={`chip ${statusFilter === s ? 'chip-active' : ''}`} onClick={() => setStatusFilter(s)}>
              {s === 'all' ? 'All' : s.charAt(0).toUpperCase() + s.slice(1)}
            </button>
          ))}
        </div>
      </div>

      <DataTable
        columns={[
          { key: 'name', label: 'Ad Name', sortable: true },
          { key: 'campaignName', label: 'Campaign', sortable: true },
          { key: 'status', label: 'Status', format: 'status', sortable: true },
          { key: 'impressions', label: 'Impr.', sortable: true },
          { key: 'clicks', label: 'Clicks', sortable: true },
          { key: 'ctr', label: 'CTR', sortable: true },
          { key: 'spend', label: 'Spend', format: 'currency', sortable: true },
          { key: 'cpc', label: 'CPC', sortable: true },
          { key: 'conversions', label: 'Conv.', sortable: true },
          { key: 'cpa', label: 'CPA', sortable: true },
          { key: 'roas', label: 'ROAS', sortable: true },
        ]}
        rows={rows}
        pageSize={25}
        emptyMessage="No ads found"
      />
    </PageHeader>
  );
}
