import { z } from "zod";
import type { AdCreative, Ad } from "../types/meta-api.js";

const baseStyles = `
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #1a1a2e; color: #eee; padding: 20px; }
  .container { max-width: 1200px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  .creative-info { background: #16213e; border-radius: 12px; padding: 24px; margin-bottom: 32px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .creative-info h2 { font-size: 20px; color: #e94560; margin-bottom: 16px; }
  .info-row { display: grid; grid-template-columns: 150px 1fr; gap: 12px; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #0f3460; }
  .info-row:last-child { border-bottom: none; }
  .info-label { color: #999; font-weight: 600; font-size: 13px; }
  .info-value { color: #fff; }
  .placements-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
  .placement-card { background: #16213e; border-radius: 12px; padding: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .placement-card h3 { font-size: 16px; color: #e94560; margin-bottom: 12px; display: flex; align-items: center; gap: 8px; }
  .placement-preview { background: #0f3460; border-radius: 8px; padding: 16px; margin-bottom: 12px; min-height: 200px; display: flex; align-items: center; justify-content: center; color: #777; font-size: 13px; }
  .placement-preview img { max-width: 100%; border-radius: 6px; }
  .creative-text { background: #0f3460; border-radius: 8px; padding: 12px; margin-bottom: 8px; }
  .creative-text h4 { font-size: 12px; color: #999; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }
  .creative-text p { font-size: 14px; color: #ddd; line-height: 1.5; }
  .cta-button { display: inline-block; background: #e94560; color: #fff; padding: 8px 20px; border-radius: 6px; font-weight: 600; font-size: 13px; margin-top: 8px; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any, client: any): void {
  server.tool(
    "creative_preview",
    "Creative Preview - View ad creative across multiple placements (Facebook Feed, Instagram, Stories, etc.)",
    {
      creative_id: z.string().optional().describe("Ad Creative ID"),
      ad_id: z.string().optional().describe("Ad ID (will fetch associated creative)")
    },
    async (params: { creative_id?: string; ad_id?: string }) => {
      try {
        let creativeId = params.creative_id;

        // If ad_id provided, fetch the creative ID from the ad
        if (!creativeId && params.ad_id) {
          const adResponse = await client.get(
            `/${params.ad_id}`,
            { fields: "creative" }
          ) as Ad;
          creativeId = adResponse.creative.id;
        }

        if (!creativeId) {
          throw new Error("Either creative_id or ad_id must be provided");
        }

        // Fetch creative details
        const creative = await client.get(
          `/${creativeId}`,
          {
            fields: "id,name,body,title,call_to_action_type,image_hash,image_url,video_id,thumbnail_url,link_url,object_story_spec,asset_feed_spec"
          }
        ) as AdCreative;

        // Extract creative elements
        const headline = creative.title || 
          creative.object_story_spec?.link_data?.name || 
          creative.asset_feed_spec?.titles?.[0]?.text || 
          "No headline";
        
        const bodyText = creative.body || 
          creative.object_story_spec?.link_data?.message || 
          creative.asset_feed_spec?.bodies?.[0]?.text || 
          "No body text";
        
        const description = creative.object_story_spec?.link_data?.description || 
          creative.asset_feed_spec?.descriptions?.[0]?.text || 
          "";
        
        const ctaType = creative.call_to_action_type || 
          creative.object_story_spec?.link_data?.call_to_action?.type || 
          creative.asset_feed_spec?.call_to_action_types?.[0] || 
          "LEARN_MORE";
        
        const imageUrl = creative.image_url || 
          creative.thumbnail_url || 
          "";
        
        const linkUrl = creative.link_url || 
          creative.object_story_spec?.link_data?.link || 
          creative.asset_feed_spec?.link_urls?.[0]?.website_url || 
          "";

        // Placements to preview
        const 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: "vertical-small" },
          { name: "Audience Network", icon: "🌐", format: "square" }
        ];

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Creative Preview</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>🎨 Creative Preview</h1>
    
    <div class="creative-info">
      <h2>Creative Details</h2>
      <div class="info-row">
        <div class="info-label">Creative ID</div>
        <div class="info-value">${creative.id}</div>
      </div>
      <div class="info-row">
        <div class="info-label">Name</div>
        <div class="info-value">${creative.name || 'Unnamed'}</div>
      </div>
      <div class="info-row">
        <div class="info-label">Headline</div>
        <div class="info-value">${headline}</div>
      </div>
      <div class="info-row">
        <div class="info-label">Body Text</div>
        <div class="info-value">${bodyText}</div>
      </div>
      ${description ? `
      <div class="info-row">
        <div class="info-label">Description</div>
        <div class="info-value">${description}</div>
      </div>
      ` : ''}
      <div class="info-row">
        <div class="info-label">Call to Action</div>
        <div class="info-value">${ctaType.replace(/_/g, ' ')}</div>
      </div>
      ${linkUrl ? `
      <div class="info-row">
        <div class="info-label">Link URL</div>
        <div class="info-value">${linkUrl}</div>
      </div>
      ` : ''}
    </div>

    <h2 style="margin-bottom: 20px; color: #fff;">Placement Previews</h2>
    <div class="placements-grid">
      ${placements.map(placement => `
        <div class="placement-card">
          <h3>${placement.icon} ${placement.name}</h3>
          <div class="placement-preview">
            ${imageUrl ? `<img src="${imageUrl}" alt="Creative preview">` : `<div>📷 Image preview unavailable</div>`}
          </div>
          
          <div class="creative-text">
            <h4>Body Text</h4>
            <p>${bodyText.substring(0, 150)}${bodyText.length > 150 ? '...' : ''}</p>
          </div>
          
          <div class="creative-text">
            <h4>Headline</h4>
            <p><strong>${headline}</strong></p>
          </div>
          
          ${description ? `
          <div class="creative-text">
            <h4>Description</h4>
            <p>${description.substring(0, 100)}${description.length > 100 ? '...' : ''}</p>
          </div>
          ` : ''}
          
          <div class="cta-button">${ctaType.replace(/_/g, ' ')}</div>
        </div>
      `).join('')}
    </div>
  </div>
</body>
</html>`;

        const textSummary = `Creative Preview: ${creative.name || creative.id}\n\n` +
          `Headline: ${headline}\n` +
          `Body: ${bodyText.substring(0, 200)}${bodyText.length > 200 ? '...' : ''}\n` +
          `CTA: ${ctaType}\n` +
          `${linkUrl ? `Link: ${linkUrl}\n` : ''}` +
          `Previewed across ${placements.length} placements`;

        return {
          structuredContent: {
            type: "resource",
            resource: {
              uri: "meta-ads://app/creative-preview",
              mimeType: "text/html",
              text: html
            }
          },
          content: [{ type: "text", text: textSummary }]
        };
      } catch (error: any) {
        const errorHtml = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Error</title><style>${baseStyles}</style></head>
<body><div class="container"><div class="error"><h2>⚠️ Error Loading Creative</h2><p>${error.message}</p></div></div></body>
</html>`;
        
        return {
          structuredContent: {
            type: "resource",
            resource: { uri: "meta-ads://app/creative-preview", mimeType: "text/html", text: errorHtml }
          },
          content: [{ type: "text", text: `Error: ${error.message}` }]
        };
      }
    },
    { title: "🎨 Creative Preview", readOnlyHint: true }
  );
}
