import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { MetricCard } from '../../components/data/MetricCard';
import '../../styles/base.css';
import '../../styles/google-ads-theme.css';

/* ─── Types ──────────────────────────────────────────── */
interface RecommendationItem {
  type: string;
  category: string;
  impact: 'LOW' | 'MEDIUM' | 'HIGH';
  title: string;
  description: string;
  campaignName?: string;
  estimatedImprovement?: string;
  resourceName?: string;
}

interface RecommendationsData {
  accountName?: string;
  recommendations: RecommendationItem[];
}

/* ─── Helpers ────────────────────────────────────────── */
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;
}

const impactConfig: Record<string, { color: string; bg: string; icon: string }> = {
  HIGH: { color: 'var(--gads-red)', bg: 'var(--gads-red-dim)', icon: '🔴' },
  MEDIUM: { color: 'var(--gads-yellow)', bg: 'var(--gads-yellow-dim)', icon: '🟡' },
  LOW: { color: 'var(--gads-blue)', bg: 'var(--gads-blue-dim)', icon: '🔵' },
};

const categoryColors: Record<string, { color: string; bg: string }> = {
  BIDS: { color: 'var(--gads-purple)', bg: 'var(--gads-purple-dim)' },
  BIDDING: { color: 'var(--gads-purple)', bg: 'var(--gads-purple-dim)' },
  KEYWORDS: { color: 'var(--gads-blue)', bg: 'var(--gads-blue-dim)' },
  ADS: { color: 'var(--gads-orange)', bg: 'var(--gads-orange-dim)' },
  TARGETING: { color: 'var(--gads-green)', bg: 'var(--gads-green-dim)' },
  BUDGET: { color: 'var(--gads-red)', bg: 'var(--gads-red-dim)' },
  EXTENSIONS: { color: 'var(--gads-yellow)', bg: 'var(--gads-yellow-dim)' },
  CAMPAIGN: { color: 'var(--gads-blue)', bg: 'var(--gads-blue-dim)' },
};

function getCategoryStyle(cat: string) {
  return categoryColors[cat.toUpperCase()] || { color: 'var(--gads-text-muted)', bg: 'var(--gads-border)' };
}

/* ─── App ────────────────────────────────────────────── */
export function App() {
  const [data, setData] = useState<RecommendationsData | null>((window as any).__MCP_APP_DATA__ || null);
  const [filterCategory, setFilterCategory] = useState<string>('ALL');
  const [filterImpact, setFilterImpact] = useState<string>('ALL');

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

  const byImpact = useMemo(() => {
    if (!data) return { HIGH: 0, MEDIUM: 0, LOW: 0 };
    const counts = { HIGH: 0, MEDIUM: 0, LOW: 0 };
    data.recommendations.forEach(r => {
      const key = r.impact.toUpperCase() as keyof typeof counts;
      if (key in counts) counts[key]++;
    });
    return counts;
  }, [data]);

  const categories = useMemo(() => {
    if (!data) return [];
    return [...new Set(data.recommendations.map(r => r.category.toUpperCase()))];
  }, [data]);

  const filtered = useMemo(() => {
    if (!data) return [];
    return data.recommendations.filter(r => {
      if (filterCategory !== 'ALL' && r.category.toUpperCase() !== filterCategory) return false;
      if (filterImpact !== 'ALL' && r.impact.toUpperCase() !== filterImpact) return false;
      return true;
    });
  }, [data, filterCategory, filterImpact]);

  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={{ maxWidth: 1200, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.3 }}>💡 Optimization Recommendations</h1>
        <p style={{ fontSize: 13, color: 'var(--gads-text-secondary)', marginTop: 4 }}>
          {data.accountName ? `${data.accountName} · ` : ''}{data.recommendations.length} recommendations
        </p>
      </div>

      {/* Impact KPIs */}
      <div className="stats-grid stats-grid-3" style={{ marginBottom: 16 }}>
        <MetricCard label="High Impact" value={String(byImpact.HIGH)} color="red" />
        <MetricCard label="Medium Impact" value={String(byImpact.MEDIUM)} color="yellow" />
        <MetricCard label="Low Impact" value={String(byImpact.LOW)} color="blue" />
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap', alignItems: 'center' }}>
        <span style={{ fontSize: 11, color: 'var(--gads-text-muted)' }}>Category:</span>
        <button
          onClick={() => setFilterCategory('ALL')}
          style={{
            padding: '4px 12px', borderRadius: 9999, fontSize: 11, fontWeight: 600,
            border: 'none', cursor: 'pointer',
            background: filterCategory === 'ALL' ? 'var(--gads-highlight)' : 'var(--gads-bg-accent)',
            color: filterCategory === 'ALL' ? 'white' : 'var(--gads-text-secondary)',
          }}
        >
          All
        </button>
        {categories.map(cat => {
          const style = getCategoryStyle(cat);
          return (
            <button
              key={cat}
              onClick={() => setFilterCategory(cat)}
              style={{
                padding: '4px 12px', borderRadius: 9999, fontSize: 11, fontWeight: 600,
                border: 'none', cursor: 'pointer',
                background: filterCategory === cat ? style.bg : 'var(--gads-bg-accent)',
                color: filterCategory === cat ? style.color : 'var(--gads-text-secondary)',
              }}
            >
              {cat}
            </button>
          );
        })}

        <span style={{ marginLeft: 12, fontSize: 11, color: 'var(--gads-text-muted)' }}>Impact:</span>
        {['ALL', 'HIGH', 'MEDIUM', 'LOW'].map(imp => (
          <button
            key={imp}
            onClick={() => setFilterImpact(imp)}
            style={{
              padding: '4px 12px', borderRadius: 9999, fontSize: 11, fontWeight: 600,
              border: 'none', cursor: 'pointer',
              background: filterImpact === imp ? 'var(--gads-highlight)' : 'var(--gads-bg-accent)',
              color: filterImpact === imp ? 'white' : 'var(--gads-text-secondary)',
            }}
          >
            {imp}
          </button>
        ))}
      </div>

      {/* Recommendation Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 16 }}>
        {filtered.length > 0 ? filtered.map((r, i) => {
          const impCfg = impactConfig[r.impact.toUpperCase()] || impactConfig.LOW;
          const catStyle = getCategoryStyle(r.category);

          return (
            <div key={i} className="card" style={{ display: 'flex', flexDirection: 'column', gap: 4, padding: 20 }}>
              {/* Impact + Category */}
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <span style={{
                  fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5,
                  padding: '3px 10px', borderRadius: 12, color: impCfg.color, background: impCfg.bg,
                }}>
                  {impCfg.icon} {r.impact.toUpperCase()} IMPACT
                </span>
                <span style={{
                  fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5,
                  padding: '3px 10px', borderRadius: 12, color: catStyle.color, background: catStyle.bg,
                }}>
                  {r.category.toUpperCase()}
                </span>
              </div>

              {/* Title + Desc */}
              <div style={{ fontSize: 14, fontWeight: 600, marginTop: 8, lineHeight: 1.4 }}>{r.title}</div>
              <div style={{ fontSize: 13, color: 'var(--gads-text-secondary)', lineHeight: 1.5, marginTop: 4 }}>{r.description}</div>

              {/* Campaign */}
              {r.campaignName && (
                <div style={{ fontSize: 12, color: 'var(--gads-text-muted)', marginTop: 8 }}>
                  📂 {r.campaignName}
                </div>
              )}

              {/* Estimated Improvement */}
              {r.estimatedImprovement && (
                <div style={{ marginTop: 10 }}>
                  <span style={{
                    fontSize: 11, fontWeight: 700, padding: '3px 10px', borderRadius: 12,
                    color: 'var(--gads-green)', background: 'var(--gads-green-dim)',
                  }}>
                    ⬆ {r.estimatedImprovement}
                  </span>
                </div>
              )}
            </div>
          );
        }) : (
          <div className="card" style={{ textAlign: 'center', color: 'var(--gads-text-muted)', padding: 40 }}>
            No recommendations available
          </div>
        )}
      </div>
    </div>
  );
}
