import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
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 getStatusColor(result: any): 'green' | 'yellow' | 'red' {
  if (result.verdict === 'PASS') return 'green';
  if (result.verdict === 'PARTIAL' || result.verdict === 'NEUTRAL') return 'yellow';
  return 'red';
}

function getStatusLabel(result: any): string {
  if (result.verdict === 'PASS') return 'Indexed';
  if (result.verdict === 'PARTIAL' || result.verdict === 'NEUTRAL') return 'Warning';
  return 'Error';
}

function getStatusBadgeCls(result: any): string {
  if (result.verdict === 'PASS') return 'gsc-status-indexed';
  if (result.verdict === 'PARTIAL' || result.verdict === 'NEUTRAL') return 'gsc-status-warning';
  return 'gsc-status-error';
}

function fmtDate(d: string | undefined): string {
  if (!d) return 'N/A';
  try {
    return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  } catch { return d; }
}

export function App() {
  const [data, setData] = useState<any>((window as any).__MCP_APP_DATA__ || null);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [filterStatus, setFilterStatus] = useState('all');

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

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

  const counts = useMemo(() => {
    const c = { indexed: 0, warnings: 0, errors: 0 };
    results.forEach(r => {
      const s = getStatusColor(r);
      if (s === 'green') c.indexed++;
      else if (s === 'yellow') c.warnings++;
      else c.errors++;
    });
    return c;
  }, [results]);

  const filtered = useMemo(() => {
    if (filterStatus === 'all') return results;
    const colorMap: Record<string, string> = { indexed: 'green', warnings: 'yellow', errors: 'red' };
    const target = colorMap[filterStatus];
    return results.filter(r => getStatusColor(r) === target);
  }, [results, filterStatus]);

  const toggle = (url: string) => {
    setExpanded(prev => {
      const next = new Set(prev);
      if (next.has(url)) next.delete(url); else next.add(url);
      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 }}>URL Health Inspector</h1>
      </div>

      {/* Summary Bar */}
      <div style={{
        display: 'flex', gap: 24, padding: 16, background: 'white', borderRadius: 8, marginBottom: 24, flexWrap: 'wrap',
        boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08)',
      }}>
        <div
          style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}
          onClick={() => setFilterStatus(filterStatus === 'indexed' ? 'all' : 'indexed')}
        >
          <span className="summary-dot green" />
          <strong>{counts.indexed}</strong> Indexed
        </div>
        <div
          style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}
          onClick={() => setFilterStatus(filterStatus === 'warnings' ? 'all' : 'warnings')}
        >
          <span className="summary-dot yellow" />
          <strong>{counts.warnings}</strong> Warnings
        </div>
        <div
          style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}
          onClick={() => setFilterStatus(filterStatus === 'errors' ? 'all' : 'errors')}
        >
          <span className="summary-dot red" />
          <strong>{counts.errors}</strong> Errors
        </div>
        {filterStatus !== 'all' && (
          <button
            onClick={() => setFilterStatus('all')}
            style={{
              background: 'none', border: '1px solid #dadce0', borderRadius: 4,
              padding: '4px 12px', fontSize: 12, cursor: 'pointer', color: '#5f6368',
            }}
          >
            Clear filter
          </button>
        )}
      </div>

      {/* URL Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))', gap: 16 }}>
        {filtered.map((result: any, i: number) => {
          const statusColor = getStatusColor(result);
          const isExpanded = expanded.has(result.url);

          return (
            <div key={i} className="gsc-url-card">
              {/* Card Header */}
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 12 }}>
                <span className={`traffic-light ${statusColor}`} />
                <div style={{ flex: 1, fontSize: 13, color: '#1a73e8', wordBreak: 'break-all' }} title={result.url}>
                  {result.url}
                </div>
              </div>

              {/* Status Badge */}
              <span className={getStatusBadgeCls(result)} style={{
                display: 'inline-block', padding: '4px 10px', borderRadius: 4, fontSize: 12, fontWeight: 600, marginBottom: 8,
              }}>
                {result.coverageState || getStatusLabel(result)}
              </span>

              {/* Meta */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13, color: '#5f6368' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ fontWeight: 500 }}>Last Crawled:</span>
                  <span>{fmtDate(result.lastCrawlTime)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ fontWeight: 500 }}>Verdict:</span>
                  <span>{result.verdict || 'N/A'}</span>
                </div>
                {result.robotsTxtState && (
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ fontWeight: 500 }}>Robots.txt:</span>
                    <span>{result.robotsTxtState}</span>
                  </div>
                )}
              </div>

              {/* Expand Button */}
              <button className="gsc-expand-btn" onClick={() => toggle(result.url)}>
                {isExpanded ? 'Hide Details ▲' : 'View Details ▼'}
              </button>

              {/* Expandable Details */}
              {isExpanded && (
                <div className="gsc-details">
                  {result.mobileUsability && (
                    <div className="gsc-details-section">
                      <h4>Mobile Usability</h4>
                      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
                        <span>Mobile Friendly</span>
                        <span style={{ color: result.mobileUsability.verdict === 'PASS' ? '#34a853' : '#ea4335' }}>
                          {result.mobileUsability.verdict === 'PASS' ? '✓' : '✗'}
                        </span>
                      </div>
                    </div>
                  )}

                  {result.richResults && (
                    <div className="gsc-details-section">
                      <h4>Rich Results</h4>
                      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
                        <span>Status</span>
                        <span>{result.richResults.verdict || 'N/A'}</span>
                      </div>
                    </div>
                  )}

                  <div className="gsc-details-section">
                    <h4>Index Status</h4>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
                        <span>Coverage State</span>
                        <span>{result.coverageState || 'N/A'}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
                        <span>Indexing State</span>
                        <span>{result.indexingState || 'N/A'}</span>
                      </div>
                      {result.pageFetchState && (
                        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
                          <span>Page Fetch</span>
                          <span>{result.pageFetchState}</span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {filtered.length === 0 && (
        <div style={{ textAlign: 'center', padding: 48, color: '#5f6368', fontSize: 14 }}>
          No URLs to display
        </div>
      )}
    </div>
  );
}
