import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { SparklineChart } from '../../components/charts/SparklineChart';
import '../../styles/base.css';
import '../../styles/gsc-theme.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 fmtNum(n: number): string {
  if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';
  return n.toLocaleString();
}

function fmtDate(d: string): string {
  try {
    return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  } catch { return d; }
}

function getSeverityCls(s: string): string {
  const sev = s.toLowerCase();
  if (sev === 'critical') return 'gsc-severity-critical';
  if (sev === 'moderate') return 'gsc-severity-moderate';
  return 'gsc-severity-mild';
}

function getSeverityColor(s: string): string {
  const sev = s.toLowerCase();
  if (sev === 'critical') return '#ea4335';
  if (sev === 'moderate') return '#f29900';
  return '#fbbc04';
}

function getRecommendations(severity: string): string[] {
  if (severity.toLowerCase() === 'critical') {
    return [
      'Immediate content audit required',
      'Check for technical SEO issues (404s, canonicals)',
      'Review competing SERP content',
      'Consider content refresh or rewrite',
    ];
  }
  if (severity.toLowerCase() === 'moderate') {
    return [
      'Update content with fresh information',
      'Improve internal linking to this page',
      'Check for keyword cannibalization',
      'Add new media or visual content',
    ];
  }
  return [
    'Monitor for continued decline',
    'Minor content updates may help',
    'Review analytics for user behavior changes',
  ];
}

const severityOrder: Record<string, number> = { critical: 3, moderate: 2, mild: 1 };

export function App() {
  const [data, setData] = useState<any>((window as any).__MCP_APP_DATA__ || null);
  const [expanded, setExpanded] = useState<Set<number>>(new Set());
  const [sortBy, setSortBy] = useState('severity');

  const { isConnected, error } = useApp({
    appInfo: { name: 'Content Decay Tracker', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const pages: any[] = data?.pages || [];

  const counts = useMemo(() => {
    const c = { mild: 0, moderate: 0, critical: 0 };
    pages.forEach(p => {
      const s = p.severity?.toLowerCase();
      if (s === 'critical') c.critical++;
      else if (s === 'moderate') c.moderate++;
      else c.mild++;
    });
    return c;
  }, [pages]);

  const sorted = useMemo(() => {
    const items = [...pages];
    items.sort((a, b) => {
      if (sortBy === 'severity') {
        return (severityOrder[b.severity?.toLowerCase()] || 0) - (severityOrder[a.severity?.toLowerCase()] || 0);
      }
      if (sortBy === 'absoluteLoss') return (b.absoluteLoss || 0) - (a.absoluteLoss || 0);
      if (sortBy === 'percentDrop') return (b.percentDrop || 0) - (a.percentDrop || 0);
      if (sortBy === 'daysSincePeak') return (a.daysSincePeak || 0) - (b.daysSincePeak || 0);
      return 0;
    });
    return items;
  }, [pages, sortBy]);

  const toggle = (idx: number) => {
    setExpanded(prev => {
      const next = new Set(prev);
      if (next.has(idx)) next.delete(idx); else next.add(idx);
      return next;
    });
  };

  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>;

  return (
    <div style={{ padding: 16 }}>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 24, fontWeight: 500, marginBottom: 8 }}>Content Decay Tracker</h1>
        <p style={{ fontSize: 14, color: '#5f6368' }}>Pages experiencing traffic decline</p>
      </div>

      {/* Summary Cards */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        <div style={{
          background: 'white', padding: 16, borderRadius: 8, flex: 1, minWidth: 150,
          boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08)',
        }}>
          <div style={{ fontSize: 11, textTransform: 'uppercase', color: '#5f6368', fontWeight: 600, letterSpacing: 0.5, marginBottom: 4 }}>
            Mild Decay
          </div>
          <div style={{ fontSize: 28, fontWeight: 400, color: '#fbbc04' }}>{counts.mild}</div>
        </div>
        <div style={{
          background: 'white', padding: 16, borderRadius: 8, flex: 1, minWidth: 150,
          boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08)',
        }}>
          <div style={{ fontSize: 11, textTransform: 'uppercase', color: '#5f6368', fontWeight: 600, letterSpacing: 0.5, marginBottom: 4 }}>
            Moderate Decay
          </div>
          <div style={{ fontSize: 28, fontWeight: 400, color: '#f29900' }}>{counts.moderate}</div>
        </div>
        <div style={{
          background: 'white', padding: 16, borderRadius: 8, flex: 1, minWidth: 150,
          boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08)',
        }}>
          <div style={{ fontSize: 11, textTransform: 'uppercase', color: '#5f6368', fontWeight: 600, letterSpacing: 0.5, marginBottom: 4 }}>
            Critical Decay
          </div>
          <div style={{ fontSize: 28, fontWeight: 400, color: '#ea4335' }}>{counts.critical}</div>
        </div>
      </div>

      {/* Controls */}
      <div className="gsc-filters">
        <div className="gsc-filter-group">
          <label htmlFor="sort-by">Sort by:</label>
          <select id="sort-by" className="gsc-select" value={sortBy} onChange={e => setSortBy(e.target.value)}>
            <option value="severity">Severity</option>
            <option value="absoluteLoss">Absolute Loss</option>
            <option value="percentDrop">% Drop</option>
            <option value="daysSincePeak">Days Since Peak</option>
          </select>
        </div>
      </div>

      {/* Page Cards */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {sorted.map((page: any, idx: number) => {
          const isExp = expanded.has(idx);
          const recommendations = getRecommendations(page.severity || 'Mild');
          const sevColor = getSeverityColor(page.severity || 'Mild');

          return (
            <div key={idx} className="gsc-page-card" onClick={() => toggle(idx)}>
              {/* Page Header */}
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 12 }}>
                <div style={{ flex: 1, fontSize: 14, color: '#1a73e8', wordBreak: 'break-all' }} title={page.url}>
                  {page.url}
                </div>
                <span className={getSeverityCls(page.severity || 'Mild')} style={{
                  display: 'inline-block', padding: '4px 10px', borderRadius: 4, fontSize: 12, fontWeight: 600, flexShrink: 0,
                }}>
                  {page.severity || 'Mild'}
                </span>
              </div>

              {/* Content: Sparkline + Stats */}
              <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr', gap: 16, alignItems: 'center' }}>
                {/* Sparkline */}
                <div style={{ height: 60, background: '#f8f9fa', borderRadius: 4, padding: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {page.trend && page.trend.length > 1 ? (
                    <SparklineChart values={page.trend} color={sevColor} width={180} height={44} />
                  ) : (
                    <span style={{ color: '#9ca3af', fontSize: 12 }}>No trend data</span>
                  )}
                </div>

                {/* Stats */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: 12 }}>
                  <div className="gsc-metric-item">
                    <div className="gsc-metric-label">Peak Clicks</div>
                    <div className="gsc-metric-value">{fmtNum(page.peakClicks || 0)}</div>
                  </div>
                  <div className="gsc-metric-item">
                    <div className="gsc-metric-label">Recent Clicks</div>
                    <div className="gsc-metric-value">{fmtNum(page.recentClicks || 0)}</div>
                  </div>
                  <div className="gsc-metric-item">
                    <div className="gsc-metric-label">Drop</div>
                    <div className="gsc-metric-value" style={{ color: '#ea4335' }}>
                      -{(page.percentDrop || 0).toFixed(1)}%
                    </div>
                  </div>
                  <div className="gsc-metric-item">
                    <div className="gsc-metric-label">Days Since Peak</div>
                    <div className="gsc-metric-value">{page.daysSincePeak || 0}</div>
                  </div>
                </div>
              </div>

              {/* Expandable Details */}
              {isExp && (
                <div className="gsc-details" onClick={e => e.stopPropagation()}>
                  <div className="gsc-details-section">
                    <h4 style={{ fontSize: 12, fontWeight: 600, marginBottom: 8, color: '#5f6368' }}>Timeline Details</h4>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ color: '#5f6368' }}>Peak Date:</span>
                        <span>{page.peakDate ? fmtDate(page.peakDate) : 'N/A'}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ color: '#5f6368' }}>Peak Clicks:</span>
                        <span>{fmtNum(page.peakClicks || 0)}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ color: '#5f6368' }}>Recent Average:</span>
                        <span>{fmtNum(page.recentClicks || 0)} clicks/day</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ color: '#5f6368' }}>Absolute Loss:</span>
                        <span style={{ color: '#ea4335' }}>-{fmtNum(page.absoluteLoss || 0)} clicks</span>
                      </div>
                    </div>
                  </div>

                  <div className="recommendation-box">
                    <h4>Recommended Actions</h4>
                    <ul>
                      {recommendations.map((r, ri) => <li key={ri}>{r}</li>)}
                    </ul>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {sorted.length === 0 && (
        <div style={{ textAlign: 'center', padding: 48, color: '#5f6368', fontSize: 14 }}>
          No content decay data available
        </div>
      )}
    </div>
  );
}
