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 '../../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: 'A/B Test Results', 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 experiment = data?.experiment || {};
  const variants: any[] = data?.variants || [];
  const hasSignificant = variants.some(v => v && !v.isControl && (v.confidence || 0) >= 95);

  return (
    <PageHeader title="🧪 A/B Test Results" subtitle={experiment.name || `Experiment ${experiment.id || ''}`}>
      {/* Experiment Info */}
      <div className="card" style={{ marginTop: 8 }}>
        <div className="card-header"><div className="card-title" style={{ color: '#e94560' }}>{experiment.name || 'Experiment'}</div></div>
        <div className="card-body p-md">
          {experiment.description && <p style={{ color: '#ddd', fontSize: 12, marginBottom: 8 }}>{experiment.description}</p>}
          <div style={{ display: 'grid', gap: 6 }}>
            {[
              ['Status', experiment.status],
              ['Start', experiment.start_time ? new Date(experiment.start_time).toLocaleDateString() : '—'],
              experiment.end_time && ['End', new Date(experiment.end_time).toLocaleDateString()],
            ].filter(Boolean).map(([label, value]: any, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, fontSize: 12 }}>
                <span style={{ color: '#999', minWidth: 80 }}>{label}:</span>
                <span style={{ color: '#fff', fontWeight: 600 }}>{value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {!hasSignificant && (
        <div style={{ background: 'rgba(243,156,18,0.15)', color: '#f39c12', padding: '10px 14px', borderRadius: 8, fontWeight: 600, fontSize: 13, marginTop: 8 }}>
          ⚠️ Not Yet Significant — Confidence below 95%. Continue test for more reliable results.
        </div>
      )}

      {/* Variant Cards */}
      <div className="variants-grid" style={{ marginTop: 12 }}>
        {variants.map((variant, i) => {
          if (!variant) return null;
          return (
            <div key={i} className={`variant-card ${variant.isWinner ? 'winner' : ''}`}>
              {variant.isWinner && <div className="winner-badge">🏆 Winner</div>}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: '#e94560' }}>{variant.isControl ? 'Control' : 'Treatment'}</div>
                <span style={{ background: '#0f3460', color: '#fff', padding: '2px 10px', borderRadius: 20, fontSize: 11, fontWeight: 600 }}>
                  {variant.isControl ? 'A' : 'B'}
                </span>
              </div>

              <div className="stats-grid stats-grid-2" style={{ gap: 6, marginBottom: 10 }}>
                <MetricCard label="Spend" value={`$${(variant.spend || 0).toFixed(2)}`} color="red" />
                <MetricCard label="Impressions" value={(variant.impressions || 0).toLocaleString()} color="blue" />
                <MetricCard label="CTR" value={`${(variant.ctr || 0).toFixed(2)}%`} color="green" />
                <MetricCard label="CPC" value={`$${(variant.cpc || 0).toFixed(2)}`} color="purple" />
                <MetricCard label="Conversions" value={String(variant.conversions || 0)} color="yellow" />
                <MetricCard label="ROAS" value={variant.roas > 0 ? `${variant.roas.toFixed(2)}x` : '—'} color="green" />
              </div>

              {!variant.isControl && variant.confidence !== undefined && (
                <div style={{ background: '#0f3460', borderRadius: 8, padding: 12, marginTop: 8 }}>
                  <div style={{ fontSize: 11, color: '#999', textTransform: 'uppercase', marginBottom: 6 }}>Statistical Confidence</div>
                  <div className="confidence-bar">
                    <div className="confidence-fill" style={{ width: `${variant.confidence}%` }}>
                      {variant.confidence.toFixed(1)}%
                    </div>
                  </div>
                  {variant.roasLift !== undefined && (
                    <div className={`lift-badge ${variant.roasLift >= 0 ? 'lift-positive' : 'lift-negative'}`}>
                      {variant.roasLift >= 0 ? '↑' : '↓'} {Math.abs(variant.roasLift).toFixed(1)}% ROAS Lift
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </PageHeader>
  );
}
