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 '../../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;
}

function getScoreColor(score: number): string {
  if (score > 80) return '#27ae60';
  if (score > 50) return '#f39c12';
  return '#e74c3c';
}

interface SubScore {
  name: string;
  icon: string;
  score: number;
  trend: string;
  recommendation: string;
}

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

  const { isConnected, error } = useApp({
    appInfo: { name: 'Account Health', 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 overallScore = data?.overallScore || 0;
  const overallStatus = data?.overallStatus || (overallScore > 80 ? 'Excellent' : overallScore > 50 ? 'Good' : 'Needs Attention');
  const overallColor = getScoreColor(overallScore);
  const scoreDeg = (overallScore / 100) * 360;
  const datePreset = data?.datePreset || 'last_30d';

  const subscores: SubScore[] = data?.subscores || [
    { name: 'Budget Utilization', icon: '💰', score: data?.budgetScore || 0, trend: '→', recommendation: data?.budgetRec || '' },
    { name: 'Creative Freshness', icon: '🎨', score: data?.creativeFreshnessScore || 0, trend: '↓', recommendation: data?.creativeRec || '' },
    { name: 'Audience Saturation', icon: '👥', score: data?.saturationScore || 0, trend: '↑', recommendation: data?.saturationRec || '' },
    { name: 'Conversion Efficiency', icon: '🎯', score: data?.conversionScore || 0, trend: '→', recommendation: data?.conversionRec || '' },
    { name: 'Account Activity', icon: '⚡', score: data?.activityScore || 0, trend: '→', recommendation: data?.activityRec || '' },
  ];

  return (
    <PageHeader title="💚 Account Health Score" subtitle={datePreset}>
      {/* Overall Score */}
      <div className="card" style={{ marginTop: 8, textAlign: 'center', padding: 24 }}>
        <div className="score-gauge">
          <div className="score-circle" style={{
            background: `conic-gradient(${overallColor} 0deg, ${overallColor} ${scoreDeg}deg, #0f3460 ${scoreDeg}deg, #0f3460 360deg)`,
          }}>
            <div className="score-inner">
              <div className="score-number" style={{ color: overallColor }}>{overallScore}</div>
              <div className="score-label-sm">Score</div>
            </div>
          </div>
        </div>
        <div style={{ fontSize: 18, fontWeight: 700, color: overallColor, marginBottom: 4 }}>{overallStatus}</div>
        <div style={{ color: '#999', fontSize: 13 }}>Account health for {datePreset}</div>
      </div>

      {/* Sub-scores */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 10, marginTop: 8 }}>
        {subscores.map((sub, i) => {
          const color = getScoreColor(sub.score);
          return (
            <div key={i} className="subscore-card">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#fff' }}>{sub.icon} {sub.name}</div>
                <div style={{ fontSize: 16 }}>{sub.trend}</div>
              </div>
              <div style={{ fontSize: 20, fontWeight: 700, color, marginBottom: 4 }}>{sub.score}/100</div>
              <div className="subscore-bar">
                <div className="subscore-fill" style={{ width: `${sub.score}%`, background: color }} />
              </div>
              {sub.recommendation && (
                <div className="subscore-rec">{sub.recommendation}</div>
              )}
            </div>
          );
        })}
      </div>
    </PageHeader>
  );
}
