import React, { useState } 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 { FunnelChart } from '../../components/charts/FunnelChart';
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 { isConnected, error } = useApp({
    appInfo: { name: 'Funnel Analyzer', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

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

  // Calculate conversion rates and dropoffs
  const stageStats = stages.map((s, i) => {
    const prevValue = i > 0 ? stages[i - 1].value : s.value;
    const convRate = prevValue > 0 ? (s.value / prevValue) * 100 : 0;
    const dropoff = i > 0 && prevValue > 0 ? ((prevValue - s.value) / prevValue) * 100 : 0;
    return { ...s, convRate, dropoff };
  });

  const funnelStages = stageStats.map(s => ({ label: s.name || s.label, value: s.value || 0 }));

  return (
    <PageHeader title="🔄 Funnel Analyzer" subtitle={datePreset}>
      <FunnelChart stages={funnelStages} showDropoff title="Conversion Funnel" />

      {/* Detailed stage breakdown */}
      <div className="card" style={{ marginTop: 8 }}>
        <div className="card-header"><div className="card-title">Stage Details</div></div>
        <div className="card-body p-0">
          <table className="data-table">
            <thead>
              <tr>
                <th>Stage</th>
                <th>Volume</th>
                <th>Conversion Rate</th>
                <th>Drop-off</th>
              </tr>
            </thead>
            <tbody>
              {stageStats.map((s, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 600, color: '#fff' }}>{s.name || s.label}</td>
                  <td style={{ fontFamily: 'monospace' }}>{(s.value || 0).toLocaleString()}</td>
                  <td>{i > 0 ? <span style={{ color: '#27ae60', fontWeight: 600 }}>{s.convRate.toFixed(2)}%</span> : '—'}</td>
                  <td>{i > 0 ? <span style={{ color: '#e74c3c', fontWeight: 600 }}>{s.dropoff.toFixed(2)}%</span> : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Cost per stage */}
      <div className="card" style={{ marginTop: 8 }}>
        <div className="card-header"><div className="card-title">💰 Cost Per Stage</div></div>
        <div className="card-body p-sm">
          <div className="stats-grid stats-grid-4" style={{ gap: 6 }}>
            <MetricCard label="CPM" value={costs.cpm > 0 ? `$${costs.cpm.toFixed(2)}` : '—'} color="blue" />
            <MetricCard label="CPC" value={costs.cpc > 0 ? `$${costs.cpc.toFixed(2)}` : '—'} color="purple" />
            <MetricCard label="CPL" value={costs.cpl > 0 ? `$${costs.cpl.toFixed(2)}` : '—'} color="yellow" />
            <MetricCard label="CPA" value={costs.cpa > 0 ? `$${costs.cpa.toFixed(2)}` : '—'} color="red" />
          </div>
        </div>
      </div>
    </PageHeader>
  );
}
