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 { Card } from '../../components/layout/Card';
import { SplitLayout } from '../../components/layout/SplitLayout';
import { StatusBadge } from '../../components/data/StatusBadge';
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 GaugeChart({ value, max = 100, label, color }: { value: number; max?: number; label: string; color: string }) {
  const pct = Math.min(1, value / max);
  const r = 60, cx = 80, cy = 70;
  const startAngle = Math.PI, endAngle = startAngle + pct * Math.PI;
  const x1 = cx + r * Math.cos(startAngle), y1 = cy + r * Math.sin(startAngle);
  const x2 = cx + r * Math.cos(endAngle), y2 = cy + r * Math.sin(endAngle);
  const largeArc = pct > 0.5 ? 1 : 0;
  return (
    <div className="gauge-container">
      <svg viewBox="0 0 160 90" className="gauge-svg">
        <path d={`M${cx - r},${cy} A${r},${r} 0 0,1 ${cx + r},${cy}`} fill="none" stroke="#2a2d3a" strokeWidth={12} strokeLinecap="round" />
        {pct > 0 && <path d={`M${x1},${y1} A${r},${r} 0 ${largeArc},1 ${x2},${y2}`} fill="none" stroke={color} strokeWidth={12} strokeLinecap="round" />}
        <text x={cx} y={cy - 5} textAnchor="middle" fill="#e2e8f0" fontSize="22" fontWeight="700">{value}</text>
        <text x={cx} y={cy + 12} textAnchor="middle" fill="#94a3b8" fontSize="10">/ {max}</text>
      </svg>
      <div className="gauge-label">{label}</div>
    </div>
  );
}

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

  const { isConnected, error } = useApp({
    appInfo: { name: 'Deep Scan Report', 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 phone = data.phoneNumber || data.phone || '';
  const carrier = data.carrier || {};
  const callerName = data.callerName || {};
  const fraudRisk = data.fraudScore ?? data.fraudRisk ?? data.riskScore ?? 0;
  const lineType = carrier.type || data.lineType || data.type || 'Unknown';
  const riskColor = fraudRisk > 70 ? '#ef4444' : fraudRisk > 40 ? '#f59e0b' : '#22c55e';

  return (
    <div>
      <PageHeader title={`🔍 ${phone}`} subtitle="Phone number intelligence report" />
      <SplitLayout ratio="50/50" gap="md">
        <div>
          <Card title="Carrier Information">
            <div className="kv-list" style={{ background: 'transparent', border: 'none' }}>
              <div className="kv-row"><span className="kv-label">Carrier</span><span className="kv-value">{carrier.name || data.carrierName || 'Unknown'}</span></div>
              <div className="kv-row"><span className="kv-label">Line Type</span><span className="kv-value">{lineType}</span></div>
              <div className="kv-row"><span className="kv-label">Mobile Country Code</span><span className="kv-value">{carrier.mobileCountryCode || data.countryCode || '—'}</span></div>
              <div className="kv-row"><span className="kv-label">Mobile Network Code</span><span className="kv-value">{carrier.mobileNetworkCode || '—'}</span></div>
            </div>
          </Card>
          <Card title="Caller Name (CNAM)">
            <div className="kv-list" style={{ background: 'transparent', border: 'none' }}>
              <div className="kv-row"><span className="kv-label">Name</span><span className="kv-value">{callerName.callerName || callerName.name || '—'}</span></div>
              <div className="kv-row"><span className="kv-label">Type</span><span className="kv-value">{callerName.callerType || callerName.type || '—'}</span></div>
            </div>
          </Card>
        </div>
        <div>
          <Card title="Fraud Risk Assessment">
            <GaugeChart value={fraudRisk} max={100} label="Fraud Risk Score" color={riskColor} />
          </Card>
          <Card title="Location">
            <div className="kv-list" style={{ background: 'transparent', border: 'none' }}>
              <div className="kv-row"><span className="kv-label">Country</span><span className="kv-value">{data.countryCode || data.country || '—'}</span></div>
              <div className="kv-row"><span className="kv-label">Region</span><span className="kv-value">{data.region || data.state || '—'}</span></div>
              <div className="kv-row"><span className="kv-label">City</span><span className="kv-value">{data.city || '—'}</span></div>
              <div className="kv-row"><span className="kv-label">National Format</span><span className="kv-value">{data.nationalFormat || data.formatted || phone}</span></div>
            </div>
          </Card>
        </div>
      </SplitLayout>
    </div>
  );
}
