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 [statusFilter, setStatusFilter] = useState<string>('all');
  const [search, setSearch] = useState('');

  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 summary = data?.summary || {};
  const campaigns: any[] = data?.campaigns || [];
  const datePreset = data?.datePreset || 'last_7d';

  const filteredCampaigns = useMemo(() => {
    return campaigns.filter(c => {
      if (statusFilter !== 'all' && (c.status || '').toLowerCase() !== statusFilter) return false;
      if (search) {
        const q = search.toLowerCase();
        return (c.name || '').toLowerCase().includes(q) || (c.objective || '').toLowerCase().includes(q);
      }
      return true;
    });
  }, [campaigns, statusFilter, search]);

  const rows = useMemo(() => filteredCampaigns.map((c, i) => ({
    id: c.id || String(i),
    name: c.name || 'Unknown',
    status: c.status || 'UNKNOWN',
    objective: (c.objective || '').replace('OUTCOME_', ''),
    budget: `$${(c.budget || 0).toFixed(2)}`,
    spend: `$${(c.spend || 0).toFixed(2)}`,
    impressions: (c.impressions || 0).toLocaleString(),
    ctr: `${(c.ctr || 0).toFixed(2)}%`,
    cpc: `$${(c.cpc || 0).toFixed(2)}`,
    cpa: c.conversions > 0 ? `$${(c.cpa || 0).toFixed(2)}` : '—',
    roas: c.roas > 0 ? `${(c.roas || 0).toFixed(2)}x` : '—',
    budgetPacing: c.budgetPacing || 0,
  })), [filteredCampaigns]);

  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(campaigns.map(c => (c.status || '').toLowerCase())))];

  return (
    <PageHeader title="📊 Campaign Dashboard" subtitle={`${datePreset} · ${campaigns.length} campaigns`}>
      <div className="stats-grid stats-grid-6" style={{ marginTop: 8, marginBottom: 8 }}>
        <MetricCard label="Total Spend" value={`$${(summary.totalSpend || 0).toFixed(2)}`} color="red" />
        <MetricCard label="Impressions" value={(summary.totalImpressions || 0).toLocaleString()} color="blue" />
        <MetricCard label="Avg CTR" value={`${(summary.avgCtr || 0).toFixed(2)}%`} color="green" />
        <MetricCard label="Avg CPC" value={`$${(summary.avgCpc || 0).toFixed(2)}`} color="purple" />
        <MetricCard label="Conversions" value={(summary.totalConversions || 0).toLocaleString()} color="yellow" />
        <MetricCard label="ROAS" value={`${(summary.overallRoas || 0).toFixed(2)}x`} color="green" />
      </div>

      <div style={{ display: 'flex', gap: 8, marginBottom: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        <input type="text" className="search-input" placeholder="Search campaigns…" 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: 'Campaign', sortable: true },
          { key: 'status', label: 'Status', format: 'status', sortable: true },
          { key: 'objective', label: 'Objective', sortable: true },
          { key: 'budget', label: 'Budget', format: 'currency', sortable: true },
          { key: 'spend', label: 'Spend', format: 'currency', sortable: true },
          { key: 'impressions', label: 'Impressions', sortable: true },
          { key: 'ctr', label: 'CTR', sortable: true },
          { key: 'cpc', label: 'CPC', sortable: true },
          { key: 'cpa', label: 'CPA', sortable: true },
          { key: 'roas', label: 'ROAS', sortable: true },
        ]}
        rows={rows}
        pageSize={20}
        emptyMessage="No campaigns found"
      />
    </PageHeader>
  );
}
