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

const DEFAULT_PLACEMENTS = [
  { name: 'Facebook Feed', icon: '📱', format: 'square' },
  { name: 'Instagram Feed', icon: '📷', format: 'square' },
  { name: 'Instagram Story', icon: '📲', format: 'vertical' },
  { name: 'Facebook Right Column', icon: '💻', format: 'small' },
  { name: 'Audience Network', icon: '🌐', format: 'square' },
];

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

  const { isConnected, error } = useApp({
    appInfo: { name: 'Creative Preview', 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 creative = data?.creative || data || {};
  const headline = creative.headline || creative.title || 'No headline';
  const bodyText = creative.bodyText || creative.body || 'No body text';
  const description = creative.description || '';
  const ctaType = (creative.ctaType || creative.call_to_action_type || 'LEARN_MORE').replace(/_/g, ' ');
  const imageUrl = creative.imageUrl || creative.image_url || creative.thumbnail_url || '';
  const linkUrl = creative.linkUrl || creative.link_url || '';
  const placements = data?.placements || DEFAULT_PLACEMENTS;

  return (
    <PageHeader title="🎨 Creative Preview" subtitle={creative.name || creative.id || 'Ad Creative'}>
      {/* Creative Details */}
      <div className="card" style={{ marginTop: 8 }}>
        <div className="card-header"><div className="card-title">Creative Details</div></div>
        <div className="card-body p-md" style={{ display: 'grid', gap: 8 }}>
          {[
            ['Creative ID', creative.id],
            ['Name', creative.name || 'Unnamed'],
            ['Headline', headline],
            ['Body Text', bodyText],
            description && ['Description', description],
            ['Call to Action', ctaType],
            linkUrl && ['Link URL', linkUrl],
          ].filter(Boolean).map(([label, value]: any, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 8, padding: '6px 0', borderBottom: '1px solid #0f3460' }}>
              <span style={{ color: '#999', fontWeight: 600, fontSize: 12 }}>{label}</span>
              <span style={{ color: '#fff', fontSize: 12 }}>{value}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Placement Tabs */}
      <div className="tab-group" style={{ marginTop: 12 }}>
        {placements.map((p: any, i: number) => (
          <button key={i} className={`tab ${activePlacement === i ? 'tab-active' : ''}`} onClick={() => setActivePlacement(i)}>
            {p.icon} {p.name}
          </button>
        ))}
      </div>

      {/* Placement Preview */}
      <div className="placements-grid">
        {placements.map((placement: any, i: number) => (
          <div key={i} className="placement-card" style={{ display: activePlacement === i ? 'block' : 'none' }}>
            <h3>{placement.icon} {placement.name}</h3>
            <div className="placement-preview" style={{ minHeight: placement.format === 'vertical' ? 200 : 160 }}>
              {imageUrl ? (
                <img src={imageUrl} alt="Creative preview" style={{ maxWidth: '100%', borderRadius: 4 }} />
              ) : (
                <div style={{ textAlign: 'center', color: '#777' }}>📷 Image preview unavailable</div>
              )}
            </div>
            <div style={{ background: '#0f3460', borderRadius: 6, padding: 10, marginBottom: 6 }}>
              <div style={{ fontSize: 10, color: '#999', textTransform: 'uppercase', marginBottom: 4 }}>Body Text</div>
              <div style={{ fontSize: 12, color: '#ddd', lineHeight: 1.4 }}>{bodyText.substring(0, 150)}{bodyText.length > 150 ? '…' : ''}</div>
            </div>
            <div style={{ background: '#0f3460', borderRadius: 6, padding: 10, marginBottom: 6 }}>
              <div style={{ fontSize: 10, color: '#999', textTransform: 'uppercase', marginBottom: 4 }}>Headline</div>
              <div style={{ fontSize: 13, color: '#fff', fontWeight: 600 }}>{headline}</div>
            </div>
            {description && (
              <div style={{ background: '#0f3460', borderRadius: 6, padding: 10, marginBottom: 6 }}>
                <div style={{ fontSize: 10, color: '#999', textTransform: 'uppercase', marginBottom: 4 }}>Description</div>
                <div style={{ fontSize: 12, color: '#ddd' }}>{description.substring(0, 100)}{description.length > 100 ? '…' : ''}</div>
              </div>
            )}
            <div style={{ display: 'inline-block', background: '#e94560', color: '#fff', padding: '6px 16px', borderRadius: 6, fontWeight: 600, fontSize: 12, marginTop: 4 }}>
              {ctaType}
            </div>
          </div>
        ))}
      </div>
    </PageHeader>
  );
}
